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
Using PHP 5.5'S Password_Hash and Password_Verify Function
Upgrading My Encryption Library from Mcrypt to Openssl
List of All Locales and Their Short Codes
Getting Checkbox Values on Submit
Execute PHP Script in Cron Job
Keeping Session Alive With Curl and PHP
How to Check Whether Mod_Rewrite Is Enable on Server
Curl and PHP - How to Pass a Json Through Curl by Put,Post,Get
Remove Index.PHP from Url - Codeigniter 2
How to Set Order by Params Using Prepared Pdo Statement
How to Bind MySQLi Bind_Param Arguments Dynamically in PHP
Is There Way to Use Two PHP Versions in Xampp
Getting the Names of All Files in a Directory With PHP
PHP Simplexml How to Save the File in a Formatted Way
How to Upload Multiple Files Using PHP, Jquery and Ajax