1

The following PHP function finds the node in the multi-dimensional array by matching its key:

<?php
function & findByKey($array, $key) {
    foreach ($array as $k => $v) {
        if(strcasecmp($k, $key) === 0) {
            return $array[$k];
        } elseif(is_array($v) && ($find = findByKey($array[$k], $key))) {
            return $find;
        }
    }

    return null;
}


$array = [
    'key1' => [
        'key2' => [
            'key3' => [
                'key5' => 1
            ],
            'key4' => '2'
        ]
    ]
];

$result = findByKey($array, 'key3');

I want the function to return a reference to the node so that if I change $result then the original $array also changes (like Javascript objects).

<?php
array_splice($result, 0, 0, '2');

//Changes $array also since the `$result` is a reference to:
$array['key1']['key2']['key3']

How can I do this?

1
  • Tried using array_column ? That should be a start Commented Aug 23, 2017 at 11:49

1 Answer 1

1

You need to do two things:

1) specify your $array parameter as a reference:

function & findByKey(&$array, $key) {

2) assign the variable $result by reference using the &:

$result = &findByKey($array, 'key3');

Since you are calling your function recursively, you need to also assign $find by reference as well.

altogether:

function & findByKey(&$array, $key) {
    foreach ($array as $k => $v) {
        if(strcasecmp($k, $key) === 0) {
            return $array[$k];
        } elseif(is_array($v) && ($find = &findByKey($array[$k], $key))) {
            return $find;
        }
    }

    return null;
}


$result = &findByKey($array, 'key3');
$result = 'changed';
print_r($array);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.