0

I'm trying to add indexed arrays to a final array on a certain index. So far, I have tried this:

$lista = array();
$id = '1234';

$lista2 = array(
    'chave1' => 'valor1',
    'chave2' => 'valor2',
    'chave3' => 'valor3'
);

$lista3 = array(
    'chave4' => 'valor4',
    'chave5' => 'valor5',
    'chave6' => 'valor6'
);

array_push($lista[$id], $lista2);
array_push($lista[$id], $lista3);

But it's not working. The final array on the $id index has NULL value. What am I missing? Can someone help me?

2 Answers 2

1

array_push is used for appending something to the end of array, it should not be used with specific key. You want something more like this:

<?php
$lista = array();
$id = '1234';

$lista2 = array(
    'chave1' => 'valor1',
    'chave2' => 'valor2',
    'chave3' => 'valor3'
);

$lista3 = array(
    'chave4' => 'valor4',
    'chave5' => 'valor5',
    'chave6' => 'valor6'
);

$lista[$id] = $lista2 + $lista3;

print_r($lista);

output:

Array
(
    [1234] => Array
        (
            [chave1] => valor1
            [chave2] => valor2
            [chave3] => valor3
            [chave4] => valor4
            [chave5] => valor5
            [chave6] => valor6
        )

)

EDIT:

If you need it in loop (which does not look correct, so you should reconsider structure of your code...):

<?php
$lista = array();
$id = '1234';

$lista1 = array(
    'chave7' => 'valor7',
    'chave8' => 'valor8',
    'chave9' => 'valor9'
);

$lista2 = array(
    'chave1' => 'valor1',
    'chave2' => 'valor2',
    'chave3' => 'valor3'
);

$lista3 = array(
    'chave4' => 'valor4',
    'chave5' => 'valor5',
    'chave6' => 'valor6'
);
$lista[$id] = [];
for ($i = 1; $i <= 3; $i++) {
    $lista[$id] += ${'lista' . $i};
}
print_r($lista);
Sign up to request clarification or add additional context in comments.

4 Comments

Oh I see.. But what if I'm inside a loop? Instead of 2 arrays, I need to add 35 arrays like that?
Loop of arrays sounds like a bad design and you potentially need to reconsider your code. However, there is a way to do this: $lista[$id] += ${'lista' . $i}; where $i is iterative variable in your for loop, if your arrays are indexed... But as I said this is a bad pattern
I tested your coude here, It's funny cause it's adding only $lista1 and $lista3 to the main array.
@churros It is adding all of those, just that I wrote same key names for array 1 and 2. My bad. See update
0

Try assigning the value directly: $lista[$id] = $lista2;

1 Comment

I need to add more than one array.

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.