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
?>
Written by Ekrem Büyükkaya
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#