Best Way to Clear a PHP Array's Values

Efficiency of using foreach loops to clear a PHP array's values

Like Zack said in the comments below you are able to simply re-instantiate it using

$foo = array(); // $foo is still here

If you want something more powerful use unset since it also will clear $foo from the symbol table, if you need the array later on just instantiate it again.

unset($foo); // $foo is gone
$foo = array(); // $foo is here again

If we are talking about very large tables I'd probably recommend

$foo = null; 
unset($foo);

since that also would clear the memory a bit better. That behavior (GC) is however not very constant and may change over PHP versions. Bear in mind that re-instantiating a structure is not the same as emptying it.

PHP array delete by value (not key)

Using array_search() and unset, try the following:

if (($key = array_search($del_val, $messages)) !== false) {
unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

How can I remove all data in an array - PHP

When you want to clear the complete array, why not using unset($data)?
Your code does not work they way as you expect it, because in your loop you are defining a new variable $item. You are then unsetting this variable $item which has no effect on original the values of your $data array.
If you want to use a loop you need to define it like that:

foreach ($data as $index => $item) {
unset($data[$index]);
}

This clears all values from $data but not unsetting the $data array itself.
A more efficient way compared to the loop would be to just assign a empty array to $data like:

$data = [];

How to unset entire array in PHP?

You ought to use:
unset ( $err );

How do I clear the values in a PHP array while maintaining its keys?

Without knowing exactly what your memory/performance/object-management needs are, it's hard to say what's best. Here are some "I just want something short" alternatives:

$array = array_fill_keys(array_keys($a),""); // Simple, right?

$array = array_map(function(){return "";},$a); // More flexible but easier to typo

If you have an array that's being passed around by reference and really want to wipe it, direct iteration is probably your best bet.

foreach($a as $k => $v){
$a[$k] = "";
}

Iteration with references:

/* This variation is a little more dangerous, because $v will linger around
* and can cause bizarre bugs if you reuse the same variable name later on,
* so make sure you unset() it when you're done.
*/
foreach($a as $k => &$v){
$v = "";
}
unset($v);

If you have a performance need, I suggest you benchmark these yourself with appropriately-sized arrays and PHP versions.

Reset/remove all values in an array in PHP

You can use a foreach to reset the values;

foreach($poll_options as $k => $v) {
$poll_options[$k] = 0;
}

Deleting an element from an array in PHP

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Deleting a single array element

If you want to delete just one array element you can use unset() or alternatively \array_splice().

If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.

unset()

Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete

Output:

[
[0] => a
[2] => c
]

\array_splice() method

If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values(), which will convert all keys to numerical keys.

\array_splice() needs the offset, not the key, as the second parameter.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete

Output:

[
[0] => a
[1] => c
]

array_splice(), same as unset(), take the array by reference. You don’t assign the return values of those functions back to the array.

Deleting multiple array elements

If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.

\array_diff() method

If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change the keys of the array.

Code:

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete

Output:

[
[1] => b
]

\array_diff_key() method

If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete

Output:

[
[1] => b
]

If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.

\array_filter() method

If you want to delete all elements with a specific value in the array you can use \array_filter().

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});

Output:

[
[0] => a
[1] => c
]

Remove empty array elements

As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

print_r(array_filter($linksArray));

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback:

// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));

// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));

// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));

Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray));

How to delete the value inside the array in PHP

You can use array_walk

array_walk($arr, function(&$v, $k){
unset($v['Phone']);
});


Related Topics



Leave a reply



Submit