Why is it that it's ok to increment character but not decrement with PHP?
PHP
<?php
$a = "a";
echo $a. "<br>"; //a
echo ++$a. "<br>"; //b
echo --$a. "<br>"; //b
>
Is there a simple way as --$a
to decrement a charrater?
There was a solution by using chr
.
C style increment and decrement operators represented by ++ and -- respectively are defined in PHP also. As the name suggests, ++ the increment operator increments value of operand variable by 1. The Decrement operator -- decrements the value by 1.
There is no difference between ++$j and $j++ unless the value of $j is being tested, assigned to another variable, or passed as a parameter to a function.
The decrement operator is represented by two minus signs in a row. They would subtract 1 from the value of whatever was in the variable being decremented. The precedence of increment and decrement depends on if the operator is attached to the right of the operand (postfix) or to the left of the operand (prefix).
There is no direct way to decrement alphabets. But with a simple function you can achieve it:
function decrementLetter($Alphabet) {
return chr(ord($Alphabet) - 1);
}
Source, thanks to Ryan O'Hara
There is no simple way, especially if you start with multi-character strings like 'AA'
.
As far as I can ascertain, the PHP Internals team couldn't decide what to do when
$x = 'A';
$x--;
so they simply decided not to bother implementing the character decrementor logic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With