Search code examples
phploopsfor-loopforeachphp-7.3

Multidimensional array looses its index when having no value attached


Trying to find the best array structure to iterate over multidimensional arrays.

Requirements:

1) "Title" should be able to be found through index.

2) "Balance" values should be able to be iterated over.

Observation:

Assuming above requirement the only array that fulfills the requirements is array_3. array_3 assumes that "balance" values are bundled in an array.

Questions:

1) How come the title looses its index in array_2 and array_3 in situation where title has not been assigned a value ?

2) How come (in array_1 and array_2) the value 10 gets attached as value to "balance" but value 20 gets its own index ?

3) Is there a better way to build the array assuming above requirement?

My code:

<?php

$array_1 = [
  'title',
  'balance' =>
    10,
    20,
];

$array_2 = [
  'title' => '',
  'balance' =>
    10,
    20,
];



$array_3 = [
  'title' => '',
  'balance' => [
    10,
    20,
    ]
];

// Prints

print_r($array_1);
print_r($array_2);
print_r($array_3);

// Access values through echo.

print_r($array_1['balance']) . "\n";
echo $array_2['balance'] . "\n";
echo $array_3['balance'][0] . "\n";
echo $array_3['balance'][1] . "\n";

// Loops

for ($i=0; $i < count($array_3) ; $i++) {
  echo "looping over array:" . $array_3['balance'][$i] . "\n";
}

foreach ($array_3['balance'] as $key => $value) {
  echo "key:" . $key . " " . "value:" . $value . "\n";

}

Solution

  • 1 - the title doesn't loose it's index. In the first array, the title is not an index, but is a value. Have a look at the print_r() results...

    print_r($array_1);
    

    gives...

    Array
    (
        [0] => title
        [balance] => 10
        [1] => 20
    )
    

    and

    print_r($array_2);
    

    gives...

    Array
    (
        [title] => 
        [balance] => 10
        [0] => 20
    )
    

    Using

    echo "Title=".$array_2['title'].".".PHP_EOL;
    

    just gives a blank value

    Title=.
    

    2 - in array 3 you create an array for the balance amounts

    'balance' => [
      10,
      20,
     ]
    

    where as the others have a single value

    'balance' => 10,
    20,
    

    so 20 is treated as being at the same level as balance.

    3 - The third array is about the best to how it should be done.