Some time ago during a job interview I got the task to reverse a string in PHP without using strrev
.
My first solution was something like this:
Try this:
$s = 'abcdefg';
for ($i = strlen($s)-1; $i>=0; $i--) {
$s .= $s[$i];
$s[$i] = NULL;
}
var_dump(trim($s));
Here it is PHP7 version of this:
echo "\u{202E}abcdefg"; // outs: gfedcba
//Reverse String word by word
$str = "Reverse string word by word";
$i = 0;
while ($d = $str[$i]) {
if($d == " ") {
$out = " ".$temp.$out;
$temp = "";
}
else
$temp .= $d;
$i++;
}
echo $temp.$out;
you could use substr with negative start.
you can start with for loop with counter from 1 to length of string, and call substr inside iteration with counter * -1
(which will convert the counter into negative value) and length of 1
.
So for the first time counter would be 1
and by multiplying with -1
will turn it to -1
Hence substr('abcdefg', -1, 1);
will get you g
and next iteration substr('abcdefg', -2, 1);
will get you f
and substr('abcdefg', -3, 1);
will get you e
and so on ...
$str = 'abcdefghijklmnopqrstuvwxyz';
for($i=1; $i <= strlen($str); $i++) {
echo substr($str, $i*-1, 1);
}
In Action: https://eval.in/583208
<?php
$value = 'abcdefg';
$length_value = strlen($value);
for($i = $length_value-1; $i >=0 ;$i--){
echo $value[$i];
}
?>