Why is it that it\'s ok to increment character but not decrement with PHP?
PHP
As chris85 mentioned: "Character variables can be incremented but not decremented"
PHP supports C-style pre- and post-increment and decrement operators.
Incrementing/Decrementing Operators
++$a
Pre-increment Increments $a
by one, then returns $a
.$a++
Post-increment Returns $a
, then increments $a
by one.--$a
Pre-decrement Decrements $a
by one, then returns $a.$a--
Post-decrement Returns $a
, then decrements $a
by one.Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing
NULL
values has no effect too, but incrementing them results in 1.
SRC: http://php.net/manual/en/language.operators.increment.php
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
Simple function you can achieve it:
function decrementChar($Alphabet) {
return chr(ord($Alphabet) - 1);
}
Please try with this. Output is a b a
.
$a = "a";
echo $a. "<br>";
echo $next = chr(ord($a) + 1). "<br>";
echo $prev = chr(ord($next) - 1 ). "<br>";
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