Finding the parent key of a key from an multi dimensional array in PHP

Viewed 47

I want to find the parent key of the second key in a multi dimensional array, like this:

Array
(
    [REG-4] => Array
        (
            [9007] => MANADO
            [9012] => MAMBAL
            [9078] => SEMBUNG GEDE
            [90A8] => BANYUWANGI
        )

    [REG-2] => Array
        (
            [9009] => SUBANG
            [9013] => CITEUREUP
            [9014] => BABAKAN PARI
            [9017] => CIANJUR
            [9018] => CIHERANG
            [9052] => LEGOS
            [9076] => SENTUL
            [90A0] => CARINGIN
            [9101] => MEKARSARI
            [9103] => BEKASI
        )
)

i have this code to achieve something like this => recursion(array,9007) = REG-4

function recursion($array,$needle,$parent=null){
    foreach($array as $key => $value){
        if(is_array($value)){
            recursion($value,$needle,$parent=$key);
        }
        else if($key==$needle){
            return $parent;
        }
    }
}

But my issue is that the return does not stop the recursion. After finding the correct parent, the function will still continue. Need some help if there is any wrong logic in my recursion function.

Best

1 Answers

I think if it's important to stop processing once you find the result you can do so in a few ways. You could use a static variable inside the function to keep track of whether the result has been found or not. Or you could pass a variable by-reference which would achieve the same result.

You don't need to use either of these though, you can simply check after each recursive call if it hasn't found the result yet.

function recursion($value, $needle, $key = null, $parent = null)
{
    printf('Checking %s with key "%s"'.PHP_EOL, gettype($value), $key);
    if (is_array($value)) {
        foreach ($value as $k => $child) {
            $result = recursion($child, $needle, $k, $key);
            if ($result) {
                return $result;
            }
        }
    }

    return $key == $needle ? $parent : null;
}

php index.php 9007 
Checking array with key ""
Checking array with key "REG-4"
Checking string with key "9007"
Got result REG-4
Related