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. The foreach loop will iterate over each element in the array, and you can use the unset function to remove the element from the array.

Here is an example of how you can use a foreach loop to clear an array:

<?php

$array = [1, 2, 3, 4, 5];

foreach ($array as $key => $value) {
    unset($array[$key]);
}

var_dump($array);

Watch a course Learn object oriented PHP

This will effectively clear the values of the $array variable, leaving it an empty array.

Alternatively, you can use the array_splice function to remove all elements from an array:

<?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.