0

I want to add a new element to an array using a function. This is my code:

$test = [];
$test[] = getTest('test_key');

function getTest($key){
    return [$key => 'test_value'];
}

This is the result. A multidimensional array.

Array
(
    [0] => Array
        (
            [test_key] => test_value
        )

)

But it's going one level to deep for me :) This is the desired result:

Array
(
    [test_key] => test_value

)

What part am I doing wrong? :)

0

2 Answers 2

2

You are returning an array and you push it to the $test array you had, that's why it became a multidimensional array. you may consider changing the function name, but just do so:

$test = [];
getTest($test, 'test_key');

function getTest(&$array,$key){
    $array[$key] = 'test_value';
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer. Doing a 'var_dump()' of the '$test' var results an empty var. the new updated array stays within the function. I guess making it global might work. But I don't want to do that.
Where do you place the var_dump? also, pay attention you've to pass the array by reference (see the getTest function signature), still doesn't work for you?
^^^ Pay attention to &
@MyLibary var_dump() after the function. But,
@AbraCadaver, mehehehe thanks! I deleted it. Though "how did that came here? Did I make a typo?" hehe. So bottom line it works perfectly! Thanks. What's it called the '&' so I can find more info on what it is and does?
|
0

You can merge arrays with array_merge. Here merging your result with your original array.

<?php

function getTest($key){
    return [$key => 'stool'];
}

$test = ['foo'=>'food'];
$test = array_merge($test, getTest('bar'));
print_r($test);

Output:

Array
(
    [foo] => food
    [bar] => stool
)

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.