3

Hey everyone, I have a database result that returns from a method. I need to push 4 more values onto the stack but I need to name the keys. array_push() automatically assigns an int. How can I overcome this behavior?

Array
(
    [these] => df
    [are] => df
    [the] => sdf
    [keys] => sd
    [ineed] => daf
    [0] => something
    [1] => something
    [2] => something
    [3] => something
)

The keys that are int values need to be changed. How can I do this using array_push?

5 Answers 5

6

Just like this:

$arr['anotherKey'] = "something";
$arr['yetAnotherKey'] = "something";
$arr['andSoOn'] = "something";

or

$arr = array_merge($arr, array(
    'anotherKey' => "something",
    'yetAnotherKey' => "something",
    'andSoOn' => "something"
));

...but I'd recommend the first method, since it merely adds more elements to the array, whereas the second will have a lot more overhead (though it's much more flexible in some situations).

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

Comments

3

If the four values you want to use are already in an associative array themselves, you can use + to merge the two arrays:

$array1 = array('these' => ..., 'are' => .., 'keys' => ...);
$four_entries = array('four' => ..., 'more' => ..., 'keys' => ..., '!' => ...);

$merged_array = $array1 + $four_entries;

2 Comments

Now that's cool! Thanks, had no idea. I'm unfortunately getting the exact same results tho. There is an int preceeding each new value.
Thank you.. I figured it out.. :)
3

Why not

$arr["whateveryouwant"] = something

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Comments

2

If you want to add more entries to the array, all you need to do is:

Existing array;

$array = 
{
    "these" => "df"
    "are" => "df"
    "the" => "sdf"
    "keys" => "sd"
    "ineed" => "daf"
}

Adding to the array

$array["new_key1"] = "something";
$array["new_key2"] = "something";

1 Comment

Hi Jon, thanks for the help. The first array is built a bit different than the second and admittedly, I'm not very good with arrays so I'm trying to figure out how to use your method. I already tried it before posting but I couldn't get it to work right.
2

If you want to assign the name you do not use the array_push function, you just assign the element:

$array['somekey'] = 'somevalue';

So, in short, you can't do that using array_push.

1 Comment

Ok, you probably saved me a bunch of time trying to figure it out. Thanks!

Your Answer

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