Recursively searching and removing a value from a multidimensional array in PHP

This topic contains 1 reply, has 1 voice, and was last updated by  admin February 21, 2017 at 8:27 am.

  • Creator
    Topic
  • #5055

    admin
    Keymaster

    Recursively searching and removing a value from a multidimensional array in PHP

Viewing 1 replies (of 1 total)
  • Author
    Replies
  • #5057
    Helpful
    Up
    0
    Down
    Not Helpful

    admin
    Keymaster

    Using the code

    Assuming we want to remove all the elements containing “FirstValue” from an array, for example:
    Hide Copy Code

    $value = “FirstValue”; //value/element we want to remove

    And we have the following multidimensional array:
    Hide Copy Code

    $array[“First”] = “FirstValue”;
    $array[“Second”] = “SecondValue”;
    $array[“Third”][“First”] = “FirstValue”;
    $array[“Third”][“Second”] = “SecondValue”;
    $array[“Fourth”][“Third”][“First”] = “FirstValue”;
    $array[“Fourth”][“Third”][“Second”] = “SecondValue”;
    $array[“Fifth”][“Fourth”][“Third”][“First”] = “FirstValue”;
    $array[“Fifth”][“Fourth”][“Third”][“Second”] = “SecondValue”;

    Using a simple print_r($array) on the above array, will print the following:
    Hide Shrink Copy Code

    Array
    (
    [First] => FirstValue
    [Second] => SecondValue
    [Third] => Array
    (
    [First] => FirstValue
    [Second] => SecondValue
    )

    [Fourth] => Array
    (
    [Third] => Array
    (
    [First] => FirstValue
    [Second] => SecondValue
    )

    )

    [Fifth] => Array
    (
    [Fourth] => Array
    (
    [Third] => Array
    (
    [First] => FirstValue
    [Second] => SecondValue
    )

    )

    )
    )

    In order to remove all the elements containing the value “FirstValue” from this multidimensional array, we call the recursiveRemoval($array, $value) function as follows:
    Hide Copy Code

    recursiveRemoval($array, $value);

    The recursiveRemoval function code is as follows:
    Hide Copy Code

    function recursiveRemoval(&$array, $val)
    {
    if(is_array($array))
    {
    foreach($array as $key=>&$arrayElement)
    {
    if(is_array($arrayElement))
    {
    recursiveRemoval($arrayElement, $val);
    }
    else
    {
    if($arrayElement == $val)
    {
    unset($array[$key]);
    }
    }
    }
    }
    }

    First thing we’re doing is checking if the array passed to the function is actually an array. If array passed is an array, we iterate through its elements. If the element is also an array (our array is not a one dimensional array), we recursively call the function recursiveRemoval($arrayElement, $val) again to break the multidimensional array into one dimensional arrays.

    At the end, we process the one dimensional array elements, and we compare them to the passed value we want to remove, and we unset the key of the array ($array[$key]).

Viewing 1 replies (of 1 total)

You must be logged in to reply to this topic.