1

i've very basic associative array in php

<?php
    $basic = array(
        'one'=>array(
            'value'=>'a',
            'color'=>'blue'
        )
    );
?>

now after some lines of code i've to add this array

<?php
    $more_basic = array(
        'two'=>array(
            'value'=>'b',
            'color'=>'yellow'
        )
    );
?>

the result should be like this

<?php
    $basic_result = array(
        'one'=>array(
            'value'=>'a',
            'color'=>'blue'
        ),
        'two'=>array(
            'value'=>'b',
            'color'=>'yellow'
        )
    );
?>

i'm unable to create the logic

4 Answers 4

3

Use array_merge -

$basic_result = array_merge($basic, $more_basic)

OR +

$basic_result = $basic + $more_basic
Sign up to request clarification or add additional context in comments.

1 Comment

Voted up because of $basic + $more_basic (Y)
0

You need to use array_merge

$basic_result = array_merge($basic, $more_basic);
print_r($basic_result);

Comments

0

you can set the value with the index name directly as shown below

<?php
    $basic = array(
        'one'=>array(
            'value'=>'a',
            'color'=>'blue'
        )
    );

    $basic['two'] = array(
        'value'=>'b',
        'color'=>'yellow'
    );    
?>

Comments

0

Well, PHP provides you a very clean solution for this kind of problem using array_merge()

Here, you have two options to solve your problem

1. $basic_result = $basic + $more_basic;
2. $basic_result = array_merge($basic , $more_basic);

In first case, the + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

In second case, if the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.

It should also be noted that array_merge will return NULL if any of the arguments are NULL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.