How do you remove an array element in a foreach loop?

166,588

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.

Share:
166,588
ajsie
Author by

ajsie

please delete me

Updated on May 07, 2022

Comments

  • ajsie
    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 to foreach, and you are welcome to share them.

  • Pramod Prajapati
    Pramod Prajapati over 14 years
    A 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
    Armen Michaeli about 14 years
    'unlink' unlinks files, it has nothing to do with variables or, more specifically, arrays. Perhaps you mean 'unset'?
  • Gherman
    Gherman over 9 years
    If you don't mutate an array during iteration then how do mutate an array at all? May be mean foreach or for constructions instead of iteration in general?
  • Sinister Beard
    Sinister Beard over 9 years
    This is more of a comment on another answer than an answer in and of itself.
  • Justin
    Justin over 8 years
    Some additional info about optimizing by using $key => &$tag_name stackoverflow.com/a/2008893/922522
  • Márton Tamás
    Márton Tamás over 7 years
    Note 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 the foreach loop.
  • Mr Washington
    Mr Washington over 7 years
    Note that's the trick here is to add a value to the foreach loop ;-)
  • happy_marmoset
    happy_marmoset over 7 years
    Please see @Neils answer. You will encounter unexpected bugs, especially if you work with Array of stdClasses. Do you like unexpected behavior? Me not.
  • Paritosh
    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
    namezero about 6 years
    Note that the 3rd parameter should be ARRAY_FILTER_USE_KEY in order to pass the key as $e here.
  • AbraCadaver
    AbraCadaver about 4 years
    @namezero OK why does that matter here?
  • namezero
    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
    guyaloni almost 4 years
    Important 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
    guyaloni almost 4 years
    Important 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
    userfuser over 3 years
    So, 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
    mickmackusa almost 2 years
    I never call empty() on variables that are guaranteed to be declared.