I cannot print an array with foreach

Asked

Viewed 63 times

1

I cannot 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>');
        }
    }
}
  • What are you trying to do anyway? Why so much for and foreach?

  • I am making a user table with a User array that has several keys So $user['id_usuario']['name'] $user['id_user']['cargo'] $user['id_user']['relacao']['rated']] $usuario['id_usuario']['relacao']['avaliou'] $usuario['id_usuario']['relacao']['avalio']

1 answer

1


Is returning the error:

Warning: Invalid argument supplied for foreach()

because you are trying to iterate an element that is not 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 in repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.