Last Updated: February 25, 2016
·
1.001K
· ekrembk

Increase variable and use it at the same time: ++$foo

I know you do something like this many times like me. A counter variable, you use it within the block and increase it by one at the end.

<?php
    $i = 0;
    while( $something ):
        echo $i;

        $i++;
    endwhile;
?>

This is shorter: (Also, I did not use brackets, this might be another tip for beginners :) )

<?php
    $i = 0;
    while( $something )
        echo $i++; // OR ++$i
?> 

2 Responses
Add your response

You can also use $i++, as this is a more common way to write it (also in other programming languages).

over 1 year ago ·

Be carefull as ++$i and $i++ is not the same. In the first case, the incrementation is made before getting the value, while in the second case it's after.

$i = 5;
echo $i++; // = 5
echo $i; // = 6
$i = 5;
echo ++$i; // = 6
echo $i; // = 6
over 1 year ago ·