I can not start an array with foreach

1

I can not print my array when I put a different key, it gives the error Warning: Invalid argument supplied for foreach (), how to proceed?

for ($i=0; $i < 2; $i++) { 
        $use[$i]['outrachave'] = 'some valor';
    for ($j=0; $j < 2 ; $j++) { 

        for ($k=0; $k < 2 ; $k++) { 
            $use[$i][$j][$k]= 'z';
        }
    }
}


foreach ($use as $key) {
    echo "<br/>";
    foreach ($key as $a) {

        echo('<br>');
        foreach ($a as $b) {
            print_r($b);
            echo('<br>');
        }
    }
}
    
asked by anonymous 21.06.2018 / 15:30

1 answer

1

You are returning the error:

  

Warning: Invalid argument supplied for foreach ()

Because you are trying to iterate an element that is not an array:

$use[$i]['outrachave'] = 'some valor';

To solve, you can make a condition and check if the element is an array:

if ( is_array($a) ){
  foreach ($a as $b) {
    print_r($b);
    echo "\n";
  }
} else {
  echo "Valor do elemento 'outrachave': {$a}\n";
}

Complete Code

$use = [];
for ($i=0; $i < 2; $i++) { 
  $use[$i]['outrachave'] = 'some valor';
  for ($j=0; $j < 2 ; $j++) { 
    for ($k=0; $k < 2 ; $k++) { 
      $use[$i][$j][$k]= 'z';
    }
  }
}

foreach ($use as $key) {
  echo "\n";
  foreach ($key as $a) {
    if ( is_array($a) ) {
      foreach ($a as $b) {
        print_r($b);
        echo "\n";
      }
    } else {
      echo "Valor do elemento 'outrachave': {$a}\n";
    }
  }
}

Reference

You can see it working at repl.it

    
21.06.2018 / 15:58