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.

Download  Run Code

 
The array() construct can be replaced by the short array syntax [], inspired by the JavaScript arrays:

Download  Run Code

 
The above solution works but has one flaw – it retains any references to the original array, as shown below.

Download  Run Code

 
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.

Download  Run Code

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:

Download  Run Code

That’s all about clearing values from an array in PHP.