HomeLanguagesHow to reset Array in PHP ?

How to reset Array in PHP ?

You can reset array values or clear the values very easily in PHP. There are two methods to reset the array which are discussed further in this article.

Methods:

Method 1: unset() function: The unset() function is used to unset a specified variable or entire array.

Syntax:

unset( $variable )

 

Parameters:

  • $variable: This parameter is required, it is the variable that is needed to be unset.

Return Value: This function does not return any value.

PHP




<?php
$arr1 = array(
    'neveropen',  
    'for', 
    'neveropen' 
);
  
// Print the array before reset
print_r ($arr1);
  
// Remove item from array
unset($arr1);
  
// Print the reset array
var_dump($arr1);
?>


Output:

array(3) {
  [0]=>
  string(5) "neveropen"
  [1]=>
  string(3) "for"
  [2]=>
  string(5) "neveropen"
}
PHP Notice:  Undefined variable: arr1 in 
/home/159dfdccfb89fccb996feb49cfc37d39.php on line 18

NULL

Method 2: array_diff() function: The array_diff() function accepts two or more arguments and returns an array containing values from the first array which are not present in other arrays.

Syntax:

array_diff($array1, $array2, ..., $arrayn)

Parameters: The function can take any number of arrays as parameters needed to be compared.

Return Value: This function compares the first array in parameters with the rest of the arrays and returns an array containing all the entries from $array1 that are not present in any of the other arrays.

PHP




<?php
      
$array = array("Ankesh","Saurabh","Ashish","Ashu", "Anuj", "Ajinkya");
  
//Array before reset
print_r ($array);
  
// Clear the whole values of array
$array = array_diff( $array, $array);
  
// Array after reset
print_r ($array);
      
?>


Output

Array
(
    [0] => Ankesh
    [1] => Saurabh
    [2] => Ashish
    [3] => Ashu
    [4] => Anuj
    [5] => Ajinkya
)
Array
(
)
RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS