jim
jim

Reputation:

PHP - How can I assign a name to my array key instead of an int with array_push

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?

Upvotes: 3

Views: 19984

Answers (5)

Svetlozar Angelov
Svetlozar Angelov

Reputation: 21670

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.

Upvotes: 3

searlea
searlea

Reputation: 8388

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;

Upvotes: 3

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143229

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.

Upvotes: 2

JonB
JonB

Reputation: 1320

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";

Upvotes: 2

nickf
nickf

Reputation: 546273

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).

Upvotes: 6

Related Questions