Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push multiple key and value into php array?

Tags:

arrays

php

I've searched how to push both key and value and I found this : How to push both value and key into array

But my question is how to add more than one key and value into an array?

$somearray :

Array ( 
[id] => 1645819602 
[name] => Michael George) 

I want to add this into $somearray :

[first_name] => Michael 
[last_name] => George
[work] => Google

So the output will be

Array ( 
    [id] => 1645819602 
    [name] => Michael George
    [first_name] => Michael 
    [last_name] => George
    [work] => Google) 

I know this code will not work

$arrayname[first_name] = Michael;
$arrayname[last_name] = George;
$arrayname[work] = Google;

Any help would be greatly appreciated. Thank you

like image 439
King Goeks Avatar asked Oct 30 '13 08:10

King Goeks


People also ask

How do you push a key and value in an array?

Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.

Can a Key have multiple values PHP?

To directly answer your question, no. PHP arrays can only contain one set of data for the key.

What is array_push in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


3 Answers

You have to enclose the array key in quotes and also the value if its a string.If the value is an integer then there is no need of enclosing the value in quotes.But you must enclose the value in quotes if its a string.So you need to change he code like this

$arrayname['first_name'] = 'Michael';
$arrayname['last_name'] = 'George';
$arrayname['work'] = 'Google';
like image 94
Deepu Avatar answered Sep 24 '22 14:09

Deepu


This will give you the idea:

<?

$array = array(
         [id] => 1);

$array["hello"] = "world";

print_r($array); //prints Array (
                             [id] => 1,
                             [hello] => "world")


?>
like image 33
Sal00m Avatar answered Sep 21 '22 14:09

Sal00m


Syntax for adding value into array,

$ArrayName['IndexName'] = $elementValue;
like image 35
Krish R Avatar answered Sep 23 '22 14:09

Krish R