2

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.

Martin
  • 22,212
  • 11
  • 70
  • 132
  • 1
    `$i!='$x - 1'` is looking at the literal string $x - 1. Get rid of the single quotes around the expression, replace with brackets if you like. – Jonnix Sep 30 '15 at 15:29

2 Answers2

4

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>";
}
Till Helge
  • 9,253
  • 2
  • 40
  • 56
  • +1 though just removing the quotes would have done the trick as PHP would have type cast the $x to 10. Just a side note. ;) – Jonnix Sep 30 '15 at 15:39
  • 1
    Sure. Doesn't mike it right, though. And I wouldn't respond to a question where basically just a typo causes the issue. Enough people are doing that "job". ;) – Till Helge Sep 30 '15 at 15:41
0

Try this, you should get required output

$x = "10";
for($i=0;$i<$x;$i++)
{
    if($i!= $x - 1 ) {
        echo $i."no last";
    } else if($i == $x - 1) {
        echo $i."last";
    }
    echo "<BR>";
}
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41