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


how check last loop when using loop php ?

this code, not work.

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

when 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 make code check last loop? thank you.

there other data types strings in php. doing comparison of strings, not of actual numbers.

$x = "10"; not set $x 10, "10", string built of 1 , zero. has not numerical value 10.

your comparison takes string , compares loop's counter variable using expression '$x - 1'. significant thing here. php not replace variables in single-quoted strings. here example comparison:

$foo = 42; echo '$foo bar'; // output: $foo bar echo "$foo bar"; // output: 42 bar 

so, if condition check if loop's counter not equal '$x - 1'. comparing strings works differently comparing numbers , in case not @ intended anyway. (especially because php's equality (==) , inequality operator (!=) behave unexpectedly, if you're not familiar types.)

accidentally php tries as can, why for loop works. in there compare number string. makes not sense, php makes work you. ;)

just use numerical values without 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>"; } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -