How to increase a complete string in php. Like abc
should be converted to bcd
.
I tried
$i="abc";
$i++;
echo $i; //abd
But it increases only the last character.
I searched many question like this but I did not find any solutions.
How to increase a complete string in php. Like abc
should be converted to bcd
.
I tried
$i="abc";
$i++;
echo $i; //abd
But it increases only the last character.
I searched many question like this but I did not find any solutions.
You probably have read How to increment letters like numbers in PHP?.
However, the $i++
only works on a single char.
So to get the desired output, we could simply:
str_split()
foreach()
, change, or in my case create a new output
++
<?php
$test = 'abc';
$output = '';
foreach (str_split($test) as $char) {
$output .= ++$char;
}
echo $output;
The above code will produce:
bcd
as you can try in this online demo.
A more compact solution would involve
array_map
as a loopimplode()
to stitch back the array to a string<?php
$test = 'abc';
$result = implode(array_map(fn ($c) => ++$c, str_split($test)));
echo $result;
We can do this by the following 3 steps:
$test = 'abc';
$output = '';
foreach (str_split($test) as $char) {
$output .= chr(ord($char)+1);
}
echo $output;