Skip to content
Advertisement

I keep getting a warning when I put an array in a foreach loop

Here is my code.

function displayTweets($object){
    $myArray = json_decode(json_encode($object), true);
    foreach ($myArray["statuses"] as $tweet){

It gives me a warning when I use line 3 of my code. The $object passed in the parameter is a json object and I am trying to for loop through it and display tweets. The code at first doesn’t produce warnings but then out of no where it will and it pops my page with a warning box. How can I stop this warning message? Is it okay to use $myArray[“statuses”] ?

Advertisement

Answer

Check to see if $myArray actually contains the statuses key before using it.

if(isset($myArray['statuses'])) {
  // $myArray contains statuses, execute the for loop
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement