Question

I made a small function to parse and get elements from a multidimensional array by a string written in a Unix-like path syntax.

function array_get($path, &$array) {
    $keys = preg_split('/[\/\\\]+/', $path, null, PREG_SPLIT_NO_EMPTY);
    $current = trim(array_shift($keys));
    if (is_array($array) && array_key_exists($current, $array)) {
        $path = implode("/", $keys);
        if (empty($path)) {
            // (Place the code here, see below)
            return $array[$current];
        }
        return array_get($path, $array[$current]);
    }
    return false;
}

So if I got a simple array like this

$arr = array(
    "A" => array(
        "X" => array(),
        "Y" => array(),
        "Z" => array()
    ),
    "B" => array(
        "X" => array(),
        "Y" => array(),
        "Z" => array()
    ),
    "C" => array(
        "X" => array(),
        "Y" => array(),
        "Z" => array()
    )
);

and I wish to fill it within some entries like these

$arr['A']['Z'][] = "foo";
$arr['A']['Z'][] = "bar";

I would do the same job using the following statements:

$var = array_get("A/Z", $arr);
$var[] = "foo";
$var[] = "bar";

But something went wrong.

If you try to run the code you will notice that going out of the local scope the references to the passed array will be lost.

If you wish to run a test, you can replace the placeholder comment line inside the function with these two code lines:

            $array[$current][] = "foo";
            $array[$current][] = "bar";

then you will see that the function would perform actually its own job.

Is there a way to maintain the references in output?

Was it helpful?

Solution

From the documentation, you can specify you want to return a reference by using the & character before the function name AND the function call.

<?php

function &foo(&$arr) {
  return $arr[0];
}

$a = [[]];
$b = &foo($a);
$b[0] = 'bar';
print_r($a); /* outputs [ [ 'bar' ] ] */

OTHER TIPS

You can return references.

But I find your approach really cumbersome, and it will lead to misbehaviours / maintainability / readability issues very soon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top