Reputation: 1285
Was wondering how to add the values of one array into another to save me typing the values of one array over and over:
$array_main = array(
'[1]' => '1',
'[2]' => '2',
'[3]' => '3',
'[4]' => '4'
);
$array_1 = array( $array_main, '[5]' => '5' );
This deduces:
$array_1 = array(
array(
'[1]' => '1',
'[2]' => '2',
'[3]' => '3',
'[4]' => '4'
),
'[5]' => '5'
);
But I wanted:
$array_1 = array(
'[1]' => '1',
'[2]' => '2',
'[3]' => '3',
'[4]' => '4',
'[5]' => '5'
);
So is there anything that can turn an array into a string? I've tried implode
and array_shift
but I need the whole array()
not just the values..
Upvotes: 3
Views: 1537
Reputation: 26421
Fastest way is simply use single array like following,
$array_main = array(
'[1]' => '1',
'[2]' => '2',
'[3]' => '3',
'[4]' => '4'
);
$array1 = $array_main;
$array1['[5]'] = '5';
Though if specific requirement for new array use array_merge,
$array1 = array_merge($array_main,array('[5]' => '5'));
Upvotes: 3
Reputation: 20199
Use array_merge()
$array_1 = array_merge($array_main, array('[5]' => '5'));
Upvotes: 0
Reputation: 3711
You can use merge array (don't just want to add an extra value) to merge two arrays:
<?php
$array1 = array("0" => "0", "1" => "1");
$array2 = array("a" => "a", "b" => "b");
print_r( array_merge($array1, $array2 );
?>
Prints:
Array
(
[0] => 0
[1] => 1
[a] => a
[b] => b
)
Upvotes: 0
Reputation: 7068
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
http://php.net/manual/en/function.array-merge.php
Upvotes: 3