Damian Smith
Damian Smith

Reputation: 95

elseif statement not working

I have written some script that works great, BUT I have tried to add an elseif statement in which appears to do absolutely nothing, can't figure out where I am going wrong. (Yes I am a PHP newbie, but I am trying! :)

$i = 0;
foreach($arrJobs as $job)
{
    echo "<div class=\"job-ind\">\n";
    echo '<p><a href="' . $job->url . '">' . $job->title . ', ' . $job->location . "</a></p>\n";
    echo '<p class="smaller">Reference: ' . $job->reference . "</p>\n";
    echo '<p><strong>' . $job->salary . "</strong></p>\n";
    echo "</div>\n";

    if (++$i == 5) break;

    elseif ($i == 0) {
        echo '<img src="img/no-vac.png"/>';
    }
}

Everything up the elseif statement works perfectly. Must be something simple I am missing or misunderstanding!

Upvotes: 0

Views: 1944

Answers (4)

Damian Smith
Damian Smith

Reputation: 95

Here is the working outcome, thanks for all your help!

$i = 0;
foreach($arrJobs as $job)
{
    echo "<div class=\"job-ind\">\n";
    echo '<p><a href="' . $job->url . '">' . $job->title . ', ' . $job->location . "</a></p>\n";
    echo '<p class="smaller">Reference: ' . $job->reference . "</p>\n";
    echo '<p><strong>' . $job->salary . "</strong></p>\n";
    echo "</div>\n";
    }

    if ($i = 0) {
        echo "<div class=\"job-ind\">\n";
        echo '<img src="img/no-vac.png"/>';
        echo "</div>\n";
    }

    else if (++$i == 5) {
        break;   
    }

Upvotes: 0

Timmetje
Timmetje

Reputation: 7694

Note that elseif and else if will only be considered exactly the same when using curly brackets.

if (++$i == 5) break;

elseif ($i == 0) {
    echo '<img src="img/no-vac.png"/>';
}

Won't work, change it to:

if ($i == 0) { 
    echo '<img src="img/no-vac.png"/>'; 
}
elseif (++$i == 5) {
   break;
}

elseif vs. else if

I see a lot of people discussing this in the thread. These are both correct and will both work.

The difference being :

else if() {
}

Translates to:

else {
    if(){
    }
}

And can't be used in code blocks using colons like this:

 if:
   stuff
 else if()://won't work
   //stuff
 endif;

Upvotes: 2

Matthias
Matthias

Reputation: 12259

$i will never be 0 at this location.
You increase it in the if-statement before the test (++$i).

Upvotes: 4

Dave
Dave

Reputation: 3288

basic syntax error ? you can't use the non braced short if's when doing an else if

 if (++$i == 5)  {
   break;
 } else if ($i == 0) {
   echo '<img src="img/no-vac.png"/>';
 }

notice the colour highlighting on this block compared to yours

Upvotes: 1

Related Questions