PHP Warning: Illegal string offset & Invalid argument supplied for foreach() [duplicate]

StackOverflow https://stackoverflow.com/questions/23372684

  •  12-07-2023
  •  | 
  •  

Domanda

The following two errors appear when there aren't any results:

  • Illegal string offset 'artist' in
  • Invalid argument supplied for foreach()

The code below matches results from what the user has searched and returns information back via the last.fm API, the code doing that is in a different file and isn't causing the issues.

The issues occurs when there are no search results and the foreach loop is attempting to with no data. What is needed is some sort of error catching and nothing I have tried has worked.

With it being a foreach loop a try, catch statement didn't seem to work.

if(!isset($json['results']['artistmatches']['artist'][0]))
    {  
    echo '<div class="alert  alert-danger">Artists Not Found</div>';
    }
    else 
    { 
        foreach ($json['results']['artistmatches']['artist'] as $track) 
        {
            $artist = $track['name'];
            $image = $track['image'][3]['#text'];
            $url =  preg_replace("/ /s","_" , $artist); 
            if($artist&&$image)
            {
                include('./artist_short.php');      
            }
        }

    }
È stato utile?

Soluzione

Add an if statement that checks if the result is an array.

if(is_array($json['results']['artistmatches'])) {

    foreach ($json['results']['artistmatches']['artist'] as $track) 
    {
        $artist = $track['name'];
        $image = $track['image'][3]['#text'];
        $url =  preg_replace("/ /s","_" , $artist); 

        if($artist&&$image)
        {
            include('./artist_short.php');      
        }
    }
} else {
 //handle case where the condition doesn't match.
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top