How do you remove an array element in a foreach loop?
Solution 1
If you also get the key, you can delete that item like this:
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
Solution 2
A better solution is to use the array_filter
function:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentation reads:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
Solution 3
foreach($display_related_tags as $key => $tag_name)
{
if($tag_name == $found_tag['name'])
unset($display_related_tags[$key];
}
Solution 4
Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
$result=array_search($unwantedValue,$array,true);
if($result !== false) {
unset($array[$result]);
}
The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
unset($array[$key]);
}
Check http://php.net/manual/en/function.array-search.php for more information.
Comments
-
ajsie almost 2 years
I want to loop through an array with
foreach
to check if a value exists. If the value does exist, I want to delete the element which contains it.I have the following code:
foreach($display_related_tags as $tag_name) { if($tag_name == $found_tag['name']) { // Delete element } }
I don't know how to delete the element once the value is found. How do I delete it?
I have to use
foreach
for this problem. There are probably alternatives toforeach
, and you are welcome to share them. -
Pramod Prajapati over 14 yearsA php foreach will execute on the entire array regardless. Test unsetting a value that is next in iteration. It will iterate on the offset, but the value will be null.
-
Armen Michaeli about 14 years'unlink' unlinks files, it has nothing to do with variables or, more specifically, arrays. Perhaps you mean 'unset'?
-
Gherman over 9 yearsIf you don't mutate an array during iteration then how do mutate an array at all? May be mean
foreach
orfor
constructions instead of iteration in general? -
Sinister Beard over 9 yearsThis is more of a comment on another answer than an answer in and of itself.
-
Justin over 8 yearsSome additional info about optimizing by using
$key => &$tag_name
stackoverflow.com/a/2008893/922522 -
Márton Tamás over 7 yearsNote that indexed arrays with items unset may be represented as objects instead of arrays after a
json_encode()
. You can solve this with$display_related_tags = array_values ($display_related_tags);
after theforeach
loop. -
Mr Washington over 7 yearsNote that's the trick here is to add a value to the foreach loop ;-)
-
happy_marmoset over 7 yearsPlease see @Neils answer. You will encounter unexpected bugs, especially if you work with Array of stdClasses. Do you like unexpected behavior? Me not.
-
Paritosh over 7 years@happy_marmoset Neils answer is not helping. Snippet
$projects = array_filter($projects, function ($project) { return count($project->roles) > 0; });
it converts result into object. -
namezero about 6 yearsNote that the 3rd parameter should be ARRAY_FILTER_USE_KEY in order to pass the key as $e here.
-
AbraCadaver about 4 years@namezero OK why does that matter here?
-
namezero about 4 years@AbraCadaver From the documentation (php.net/manual/en/function.array-filter.php):
ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value
Default is 0 which will pass value as the only argument to callback instead.
That said, reading the answer again in this case of course it would not matter as you claim. -
guyaloni almost 4 yearsImportant If you are interested in keeping the array as ordered array, you need to call
display_related_tags = array_values(display_related_tags);
after it. -
guyaloni almost 4 yearsImportant If you are interested in keeping the array as ordered array, you need to call
display_related_tags = array_values(display_related_tags);
after it. -
userfuser over 3 yearsSo, can we now say that it is safe, in PHP 7, to directly unset the item from the array? It definitely seems much leaner than using the
array_filter
, at least from the coder's perspective (I'm not sure about the actual implementation in the background). -
mickmackusa almost 2 yearsI never call
empty()
on variables that are guaranteed to be declared.