0

I have a simple 2D array

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

        [1] => Array
                (
                        [0] => 7
                )

        [2] => Array
                (
                )
)

lets say this is called $myArray when i try parsing it by

$i = 0;
while( $i < count($myArray) ){
    $val = $myArray[$i][0];
    echo $val;
    $i++;
}

i get an error Undefined offset: 0

can anyone lend a hand please

t q
  • 4,593
  • 8
  • 56
  • 91

2 Answers2

1

Try with:

$i = 0;
while( $i < count($myArray) ){
    $val = current($myArray[$i]);
    echo $val;
    $i++;
}
hsz
  • 148,279
  • 62
  • 259
  • 315
1

Basically you're making assumptions about the shape of you're array. Assumptions can be dangerous.

If you give me an array, I can't just assume that it has an index 0. I would need to test for it first:

<?php echo isset($myArray[$i][0]) ? $myArray[$i][0] : ''; ?>

Checking with isset() is very handy.

piers.warmers
  • 333
  • 2
  • 6