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>";
}