PDA

View Full Version : Incrementing each character in a string



Dub James
23 Oct 2010, 08:18 AM
My PHP isn't great so bare with me..

I'm trying to loop through a string and increment each character depending on an int stored in a variable.



$str = "Random string";
$chars = str_split($str, 1);

foreach($chars as $char)
{
$char++;
echo $char;
}


However, instead of printing the char to screen I'd like to replace the original character with the incremented one. Is there a simple way of doing this?

Thanks in advance.

tivy
25 Oct 2010, 04:19 PM
Ceaser cipher?



$str = "Random string";
$chars = str_split($str);
$char_shift = 1;

for($i=0; $i<count($chars); $i++) {
$chars[$i] = $chars[$i] + $char_shift;
}

$new_string = implode($chars);
echo $new_string;