Incrementing characters in loops works by decrementing, no?

So I was doing some exercise and running through this code (which produces "1. Item A", "2. Item B", etc.):

echo "\n<ol>";
for ($x='A'; $x<'G'; $x++){
    echo "<li>Item $x</li>\n";
}
echo "\n</ol>";

      

Curiously, I tried to do the opposite (which creates an infinite Zs loop):

echo "\n<ol>";
for ($x = 'Z'; $x > 'M'; $x--){
    echo "<li>Item $x</li>\n";
}
echo "\n</ol>";

      

What am I missing here?

+3
increment loops php for-loop chars


source to share


1 answer


PHP follows the Perl convention when dealing with arithmetic on character variables, not C. For example, in PHP and Perl $ a = 'Z'; $ A ++; turns $ a into 'AA', and into C a = 'Z'; A ++; becomes '[' (ASCII value 'Z' is 90, ASCII value '[' is 91). Note that character variables can be increased, but not decreased, and even only simple ASCII alphabets and numbers (az, AZ, and 0-9) are supported. Increasing / decreasing other symbolic variables has no effect, the original string is not changed.



from PHP manual link

+4


source to share







All Articles