Clear values from an array in PHP
This article demonstrates how to clear values from an array in PHP.
1. Using array() function
To clear values from an array in a single step, you can use array() language construct. The array() syntax, without any arguments, creates an empty array which can be assigned to the original array variable. For example, the following code clears all values from an array using $array = array() syntax.
|
1 2 3 4 5 6 |
<?php $array = [1, 2, 3, 4, 5]; $array = array(); print_r($array); ?> |
The array() construct can be replaced by the short array syntax [], inspired by the JavaScript arrays:
|
1 2 3 4 5 6 |
<?php $array = [1, 2, 3, 4, 5]; $array = []; print_r($array); ?> |
The above solution works but has one flaw – it retains any references to the original array, as shown below.
|
1 2 3 4 5 6 7 |
<?php $array = [1, 2, 3, 4, 5]; $array_copy = &$array; $array = []; // clear original array print_r($array_copy); // $array_copy was cleared too ?> |
In order to remove any references to the array, you can call the unset() function on it, which deletes the entire array. The following code demonstrates this by calling unset() on the array before reinstantiating it.
|
1 2 3 4 5 6 7 8 9 |
<?php $array = [1, 2, 3, 4, 5]; $array_copy = &$array; unset($array); // break references $array = []; // clear original array print_r($array_copy); // $array_copy remains unchanged ?> |
2. Using array_splice() function
The array_splice() function is used to remove a portion of the array and optionally replace it with supplied elements. It can be used as follows to empty an array and maintains all references:
|
1 2 3 4 5 6 7 8 9 |
<?php $array = [1, 2, 3, 4, 5]; $array_copy = &$array; array_splice($array, 0); // clear original array print_r($array); // $array becomes empty print_r($array_copy); // $array_copy also becomes empty ?> |
That’s all about clearing values from an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)