Efficiency of using foreach loops to clear a PHP array's values
Using a foreach loop to clear the values of an array in PHP is an efficient way to do so.
Using a foreach loop to clear the values of an array in PHP is not an efficient approach. Modifying an array while iterating over it can cause unexpected behavior and performance overhead. The standard and most efficient way to clear an array is to simply reassign it to an empty array or use unset().
Example of efficiently clearing a PHP array
<?php
$array = [1, 2, 3, 4, 5];
$array = []; // or unset($array);
var_dump($array);
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
This will effectively clear the values of the $array variable, leaving it an empty array.
Note on foreach with unset: The following example shows a common but discouraged anti-pattern. Avoid modifying an array while iterating over it, as it can lead to unpredictable results and slower performance.
Example of using foreach loops to clear a PHP array's values (discouraged)
<?php
$array = [1, 2, 3, 4, 5];
foreach ($array as $key => $value) {
unset($array[$key]);
}
var_dump($array);Alternatively, you can use the array_splice function to remove all elements from an array, though it is unnecessarily verbose compared to direct reassignment:
Example of using array_splice() function to clear a PHP array's values
<?php
$array = array(1, 2, 3, 4, 5);
array_splice($array, 0);
var_dump($array);This will also clear the values of the $array variable.