1

I was working on a way to populate an empty array.

I have this code:

$array = array();
$month = 'enero';
array_push($array, $array[$month] = array('01'));
array_push($array['enero'], '02');
print_r($array);

This returns:

Array
(
    [enero] => Array
        (
            [0] => 01
            [1] => 02
        )

    [0] => Array
        (
            [0] => 01
        )

)

The array [0] appears from nowhere and I don't know what to do. I have tried

array_push($array['enero'], '02');

But it does not work. How can I get the expected result:

Array 
( 
    [enero] => Array 
        ( 
            [0] => 01 
            [1] => 02 
        )
)
0

1 Answer 1

2

When in doubt, avoid array_push and just use [] notation. It has the advantage of automatically creating sub-arrays that don't exist (so no need to use $array[$month] = array();):

$array = array();
$month = 'enero';
$array[$month][] = '01';
$array[$month][] = '02';
print_r($array);

If you want to use array_push, you need to create the enero element first before attempting to push into it:

$array = array();
$month = 'enero';
$array[$month] = array();
array_push($array[$month], '01');
array_push($array[$month], '02');
print_r($array);

Output (for both pieces of code):

Array
(
    [enero] => Array
        (
            [0] => 01
            [1] => 02
        )    
)

Demo on 3v4l.org

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

3 Comments

Out of curiosity, why do you use array() instead of []?
@ggorlen just personal preference. I find the [ and ] around array values can get lost in a page of code but array(...) always sticks out.
Oh.... I thought this way would not work because the $array variable would be re-asigned in each loop itinerance. thank you.

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.