How to Push Both Value and Key into PHP Array

How to push both value and key into PHP array

Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.

You'll have to use

$arrayname[indexname] = $value;

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

array_push() with key value pair

So what about having:

$data['cat']='wagon';

How do i push a new key value pair to an array php?

You can add them individually like this:

$array["key"] = "value";

Collectively, like this:

$array = array(
"key" => "value",
"key2" => "value2"
);

Or you could merge two or more arrays with array_merge:

$array = array( "Foo" => "Bar", "Fiz" => "Buz" );

$new = array_merge( $array, array( "Stack" => "Overflow" ) );

print_r( $new );

Which results in the news key/value pairs being added in with the old:

Array
(
[Foo] => Bar
[Fiz] => Buz
[Stack] => Overflow
)

php- how to push key and value of an array to another array

since $new_line is an array, you probably want to merge them

array_merge($array1, $array2)

read more here http://php.net/manual/en/function.array-merge.php

Push key and value pair into multi dimensional array

is this what you are looking for?

        $samplearray = array(
array('name' => "Joe Bloggs", 'age' => "30", 'sex' => "Male", 'title' => "Mr" ),
array('name' => "Jane Bloggs", 'age' => "30", 'sex' => "Female", 'title' => "Mrs" ),
array('name' => "Little Bloggs", 'age' => "10", 'sex' => "Male", 'title' => "Master" ),
);

$samplearray[0]['othername'] = 'lalala';
echo '<pre>';
print_r($samplearray);

and this should print:

Array
(
[0] => Array
(
[name] => Joe Bloggs
[age] => 30
[sex] => Male
[title] => Mr
[othername] => lalala
)

[1] => Array
(
[name] => Jane Bloggs
[age] => 30
[sex] => Female
[title] => Mrs
)

[2] => Array
(
[name] => Little Bloggs
[age] => 10
[sex] => Male
[title] => Master
)

)



Related Topics



Leave a reply



Submit