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.
CodePudding user response:
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:
- Convert the string into an array using
str_split()
- Loop over them using a
foreach()
, change, or in my case create a new output- 'Increase' the char using
- 'Increase' the char using
<?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 loop- A short function notation
implode()
to stitch back the array to a string
<?php
$test = 'abc';
$result = implode(array_map(fn ($c) => $c, str_split($test)));
echo $result;
Try it online!
CodePudding user response:
We can do this by the following 3 steps:
- Convert each character to an unsigned integer, by using php's built-in function ord().
- Increment this integer by one (or by other number).
- Convert it back to character (using php's built-in functon chr()).
$test = 'abc';
$output = '';
foreach (str_split($test) as $char) {
$output .= chr(ord($char) 1);
}
echo $output;