How to check the last loop when using for the loop in php?

advertisements

How to check for last loop when using a for loop php ?

This is my code, But it not work.

$x = "10";
for ($i = 0; $i < $x; $i++) {
    if ($i != '$x - 1') {
        echo "$i no last";
    } else {
        echo "$i last";
    }
    echo "<br/>";
}
?>

When I test it's echo

0 last
1 no last
2 no last
3 no last
4 no last
5 no last
6 no last
7 no last
8 no last
9 no last

How can I make the code check for the last loop? Thank you.


There are other data types than strings in PHP. What you are doing is comparison of strings, not of actual numbers.

$x = "10"; will not set $x to 10, but to "10", which is the string built of a one and a zero. This has not necessarily the numerical value 10.

Your comparison then takes this string and compares it to the loop's counter variable using the expression '$x - 1'. This is the most significant thing here. PHP does not replace variables in single-quoted strings. Here is an example for comparison:

$foo = 42;
echo '$foo Bar'; // Output: $foo Bar
echo "$foo Bar"; // Output: 42 Bar

So, basically what your if condition does is to check if your loop's counter is not equal '$x - 1'. Comparing strings works completely differently than comparing numbers and in this case it does not at all what you intended anyway. (Especially because PHP's equality (==) and inequality operator (!=) sometimes behave really unexpectedly, if you're not familiar with types.)

Accidentally PHP tries to help you as much as it can, which is why your for loop works. In there you compare a number to a string. That makes not sense, but PHP makes it work for you. ;)

Just use everything as numerical values without the string notation:

<?php
$x = 10;
for($i=0; $i < $x; $i++)
{
    if($i != ($x - 1)) {
        echo $i."no last";
    } else {
        echo $i."last";
    }
    echo "<br>";
}