A line of code in PHP not understood

A line of code in PHP not understood
0

Hi everyone,

While studying PHP, I came across two codes that have the same result.

However, there is a line in the second example,echo $i;, that I could not understand its usefulness.

Besides, when I delete that line and change $i++ to echo $i++ the code produces the same result.

The code is from www.php.net
Here is a link to the lesson

<?php
/* example 1 */

$i = 1;
while ($i <= 10) {
    echo $i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>

In short, why don’t we do this in the second example:

<?php
/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i++;
endwhile;
?>

There is no reason why you can’t.

Thank you for your reply, but why have they coded:

echo $i;
    $i++;

??

Why? You would have to ask them. My guess is they wanted to make it clear that are printing $i first and then explicitly incrementing $i by 1. If a user was not aware how the ++ works when using with an echo statement, they may think that it should show the incremented value of $i vs. just the value of $i.

I’ll tell you right now:

while ($i <= 10):
    echo $i++;
endwhile;

is uncommon.

Almost always see while() {...}

The point of the example is that you can save typing a line by echoing and incrementing $i on same line.

It’s likely someone trying to be fancy., but I rarely see that approach used. If you need a loop that increments,. it just makes sense to use a for....loop