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:
- unset() Function
- array_diff() Function
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( 'zambiatek', 'for', 'zambiatek' ); // 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) "zambiatek"
[1]=>
string(3) "for"
[2]=>
string(5) "zambiatek"
}
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); ?> |
Array
(
[0] => Ankesh
[1] => Saurabh
[2] => Ashish
[3] => Ashu
[4] => Anuj
[5] => Ajinkya
)
Array
(
)



