Home > Software design >  How to increment complete string in php?
How to increment complete string in php?

Time:09-16

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:

  1. Convert the string into an array using str_split()
  2. Loop over them using a foreach() , change, or in my case create a new output
    1. '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

<?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:

  1. Convert each character to an unsigned integer, by using php's built-in function ord().
  2. Increment this integer by one (or by other number).
  3. 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;

See demo

  • Related