0

I have a multidimensional array e.g. (this can be many levels deep) and another array to be appended like this:

$another_array = array();
$array = array(
    [1] => array ()
    [2] => array ()
    [3] => array (
        [4] => array (
            [5] => array (
                [8] => array()
            )
        )
    )
)
);

I am trying to loop through it to see if a certain key exists then array append to another array

$another_array = array(); 
$keysearch = 8;

function findKey($item, $keysearch){
    foreach($array as $key => $item){
        if($key == $keysearch){
            $another_array[] = $array[$key]; // append array to another array
        }else if(is_array($item) && var_dump(findKey($item, $keysearch))==true){
            $another_array[] = $item; // append array to another array
        }
    }
}

Output I want

$another_array = [0] => array (
                [4] => array (
                    [5] => array (
                        [8] => array()
                    )
                )
            )

But it finds nothing and not append it.

14
  • Should findKey($item, $keysearch){ not be function findKey($item, $keysearch){ Commented Jul 11, 2022 at 14:26
  • @RiggsFolly means? Commented Jul 11, 2022 at 14:31
  • 2
    findKey() is never called in the code you've shown. Are you actually calling it, and if so, with what parameters? Commented Jul 11, 2022 at 14:31
  • 1
    means? You didnt create a function you just called a non-existant functoin :) Commented Jul 11, 2022 at 14:35
  • 1
    Your function is not returning anything at all. Even if you passed that array as an argument then the function wouldn't even modify that array because those are passed by value by default Commented Jul 11, 2022 at 14:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.