3

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..

4 Answers 4

3
<?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

Sign up to request clarification or add additional context in comments.

3 Comments

Yep! Knew there was something so simple I overlooked!
It would be faster if you just copy the array to a new variable, and assign a new value to it with [] like @Rikesh mentioned (in his original answer lol)
I agree with @OneTrickPony that Rikesh's method would be quicker, but this answer is most comprehensive (of what is available at this moment) and best originally answered. This is my reasoning.
3

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'));

1 Comment

Thanks !! @one Trick Pony.
0

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
)

Comments

0

Use array_merge()

$array_1 = array_merge($array_main, array('[5]' => '5'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.