'How to push multiple key and value into php array?
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
Solution 1:[1]
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';
Solution 2:[2]
This will give you the idea:
<?
$array = array(
[id] => 1);
$array["hello"] = "world";
print_r($array); //prints Array (
[id] => 1,
[hello] => "world")
?>
Solution 3:[3]
Syntax for adding value into array,
$ArrayName['IndexName'] = $elementValue;
Solution 4:[4]
This is how I add all the elements from one array to another:
<?php
$oneArray = ['d', 'e', 'f'];
$anotherArray = ['a', 'b', 'c'];
array_push($anotherArray, ...$oneArray);
//['a', 'b', 'c', 'd', 'e', 'f'];
Solution 5:[5]
Try this:
Here you need to add quotes to wrap index.
<?php
$arrayname['first_name'] = 'Michael';
$arrayname['last_name'] = 'George';
$arrayname['work'] = 'Google';
?>
Always use this when assigning any value in the array.
- Thanks
Solution 6:[6]
Don't forget to put the quote when you assigning the value.
$arrayname[first_name] = 'Michael';
$arrayname[last_name] = 'George';
$arrayname[work] = 'Google';
Solution 7:[7]
$ac_re_arr['date'] = array();
$ac_re_arr['amt'] = array();
$sql5 = mysql_query(" SELECT `id`,`bank_dues_amt`,`bank_dues` FROM `tbl_act` where `bank_dues_amt` !='' and `case_id`='$case_id' ")or die(mysql_error());
while($data5 = mysql_fetch_array($sql5))
{
$amt3 = explode('$',$data5['bank_dues_amt']);
$date3 = explode('$',$data5['bank_dues']);
$k = 0;
foreach($amt3 as $key3)
{
array_push($ac_re_arr['date'],$date3[$k]);
array_push($ac_re_arr['amt'],$amt3[$k]);
$k++;
}
}
print_r($ac_re_arr);
Output like this
Array (
[date] => Array (
[0] => 10-08-2017
[1] => 15-07-2016
)
[amt] => Array (
[0] => 5000
[1] => 2000
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepu |
| Solution 2 | Sal00m |
| Solution 3 | Krish R |
| Solution 4 | lordisp |
| Solution 5 | Anand Solanki |
| Solution 6 | King Goeks |
| Solution 7 | Tony |
