Tania Rascia Tania Rascia - 6 months ago 11
PHP Question

Return an else statement for foreach loop

I've spent about two hours trying to figure this out so finally I'm going to post it here.

I have a listing of jobs in a JSON feed that I'm pulling into PHP. I want to get all the jobs for a specific location. The location logic works fine, and I'm getting all the proper jobs.

My problem comes with getting an

else
statement to work. If I use the code below, it will return
'No jobs available'
for each instance of a job. I can use
i++
to only return it once, but it will return no matter what - whether my jobs match or not.

// This code does not work properly

foreach ( $json['jobs'] as $job ) {

$location = $job['job']['location'];

if ( $location === $current_location ) {
echo 'Job title';
} else {
echo 'No jobs available';
}
}


This will return something like:

Job title
Job title
No jobs available
Job title


So basically I need to somehow get that
else
statement out of the foreach loop, and only display once.

I'm looking for, in English: for each job, list the jobs for the current location. If the current location has no jobs available, print a statement saying "No jobs available for your location."

I apologize for such a novice logic related question. Couldn't find the correct answer after a bit of searching.

Answer

Use a variable to put this information:

$jobs = [];

foreach ( $json['jobs'] as $job ) {

    $location = $job['job']['location'];

        if ( $location === $current_location ) {
            $jobs[] = $job['job']['title'];
        }
    }
}
if(count($jobs) === 0) {
    echo '"No Jobs Found" found';
} else {
    foreach($jobs as $job) {
        echo "See this awesome job: ".$job;
    }
}