-2

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');      
            }
        }

    }
Peter Roche
  • 335
  • 2
  • 6
  • 18
  • Not a duplication, with this issue I did try that method however I didn't include certain array fields. – Peter Roche Apr 29 '14 at 19:31
  • The other one is a general solution, I attempted that and didn't work; therefore I used this website like it should, to ask the community if they knew of a solution. As you can see with the solution I wouldn't have thought of adding results and artistmatches but not artist to the is_array statement, hence that is why it is different. – Peter Roche Apr 29 '14 at 21:08
  • As I attempted to use the solution and it didn't work, I asked the community who provided a solution that worked for me, granted it uses the same is_array function however that's where the similarities end. Please don't take offence to this but I feel that your purpose is to put others down and you strike me as the sort of person that would ban me from this website if you could. I asked for help, I got that help when no other solutions I could find would work. – Peter Roche Apr 29 '14 at 21:36
  • I've posted again in discussion – Peter Roche Apr 29 '14 at 22:49

1 Answers1

1

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.
}
Peter Roche
  • 335
  • 2
  • 6
  • 18
Alex L
  • 64
  • 4