Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement character with php

Tags:

php

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 --$ato decrement a charrater?

There was a solution by using chr.

like image 420
Björn C Avatar asked May 04 '16 12:05

Björn C


People also ask

Can you do ++ in PHP?

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.

What is the difference between ++$ J and J ++ in PHP?

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.

How do you decrement a value?

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).


2 Answers

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

like image 167
Ghulam Ali Avatar answered Sep 21 '22 16:09

Ghulam Ali


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

like image 43
Mark Baker Avatar answered Sep 19 '22 16:09

Mark Baker