1

I want to create array multidimensional from looping, but the results i want don't match expectations, here's my code:

$dayCount = 5;
for($i=1;$i<=$dayCount;$i++){
   $days[] = array($i<=9?"0".$i:$i => "string");
}

Result:

Array
(
    [0] => Array
        (
            [01] => string
        )
    [1] => Array
        (
            [02] => string
        )
    [2] => Array
        (
            [03] => string
        )
    [3] => Array
        (
            [04] => string
        )
    [4] => Array
        (
            [05] => string
        )
)

My Expected Result:

Array
(
    [01] => string
    [02] => string
    [03] => string
    [04] => string
    [05] => string
)

how to make it happen? Thanks in advance

2 Answers 2

2

This notation adds an array as an element to an array.

$array[] = array(..);

The result is a 2-dimensional array. To get a one-dimensional array with self-defined strings as key, do that:

$dayCount = 5;
for($i=1;$i<=$dayCount;$i++){
  $myKey = sprintf("%02d",$i);
  $days[$myKey] = "string";
}

Attention: for keys> 9, php will generate keys of type integer with this code.

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

Comments

1

Try with this, check the demo

$dayCount = 5;
for($i=1;$i<=$dayCount;$i++){
   $days[str_pad($i,2,'0',STR_PAD_LEFT)] = "string";
}
var_dump($days);

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.