Trying to get rid of an error message

Discussion in 'PHP' started by qwikad.com, Oct 10, 2014.

  1. #1
    I am trying to set up a job search engine using careerjet's API. Everything is working fine except when the careerjet's database doesn't have jobs available for a particular query the error_log writes and posts this message:

    Warning: Invalid argument supplied for foreach() in /home1/fastjobs/public_html/index.php on line 117

    In my case line 117 is this one in the index page:

    foreach( $jobs as $job ){

    My question is is there a way to make it say a specific error message instead of a generic one when no jobs are available. Something like: Sorry, no jobs were found.

    Any help will be appreciated.

    This is the entire snippet:

          $jobs = $result->jobs ;
    
              foreach( $jobs as $job ){
               
                $counter++;
               
                echo "<div class='job'>";
                echo "<span class='title'><a target='_blank' href='". $job->url . "'>" . $job->title . "</a></span>";
                echo "<div class='location'>" . $job->locations . "</div>";
                echo "<div class='company'>" .$job->company . "</div>";
                echo "<div class='salary'>" . $job->salary . "</div>";
                echo "<div class='date'>" . $job->date . "</div>";
                echo "<div class='description'>" . $job->description . "</div>";
                echo "</div>";
              }
    
      
    Code (markup):
     
    Solved! View solution.
    qwikad.com, Oct 10, 2014 IP
  2. #2
    You could check if the variable is set and then see if the array contains more than 0 items

    $jobs = $result->jobs ;
    if (isset($jobs) && count($jobs) > 0) {
              foreach( $jobs as $job ){
              
                $counter++;
              
                echo "<div class='job'>";
                echo "<span class='title'><a target='_blank' href='". $job->url . "'>" . $job->title . "</a></span>";
                echo "<div class='location'>" . $job->locations . "</div>";
                echo "<div class='company'>" .$job->company . "</div>";
                echo "<div class='salary'>" . $job->salary . "</div>";
                echo "<div class='date'>" . $job->date . "</div>";
                echo "<div class='description'>" . $job->description . "</div>";
                echo "</div>";
              }
    } else {
        echo "No jobs found";
    }
    
    PHP:
     
    Anveto, Oct 10, 2014 IP
    sarahk likes this.
  3. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,373
    Likes Received:
    1,720
    Best Answers:
    31
    Trophy Points:
    475
    #3
    qwikad.com, Oct 10, 2014 IP
    Anveto likes this.