0

Is it possible to pass in an array to a function and return that same array object back out?

function array_setdefault($arr, $key, $dflt) {
    if (array_key_exists($key, $arr)) {
        return $arr[$key];
    }
    $arr[$key] = $dflt;
    return $arr[$key];
}

$errors = ["foo" => ["bar"]];
array_push(array_setdefault($errors, "foo", []), "bim");
array_push(array_setdefault($errors, "bla", []), "wub");

var_dump($errors);    

leads to:

array(1) {
    ["foo"]=>
    array(1) {
        [0]=>
        string(3) "bar"
    }
}

but I'd like to have:

array(2) {
    ["foo"]=>
    array(2) {
        [0]=>
        string(3) "bar"
        [1]=>
        string(3) "bim"
    }
    ["bla"]=>
    array(1) {
        [0]=>
        string(3) "wub"
    }
}

I.e. $dflt should be set on the array for the $key in case it's not been set. If it has been set previously or after it's set in the current call to array_setdefault, return what's at $arr[$key] (that is, the $dflt array object).

1 Answer 1

3

You need to use a reference argument so that changes in the function will modify the original variable, and also return a reference.

function &array_setdefault(&$arr, $key, $dflt) {
    if (!array_key_exists($key, $arr)) {
        $arr[$key] = $dflt;
    }
    return $arr[$key];
}

Putting & before the function name makes it return a reference. Putting & before a parameter makes that parameter a reference argument.

Sign up to request clarification or add additional context in comments.

3 Comments

By-ref as argument and as return value... That's going to go wrong at some point.
Is there a comparable functionalit built into the language?
I can't think of anything simple.

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.