PHP reverse string without strrev, This is very simple to reverse a String in PHP by using inbuild function strrev. But sometimes in php interview, interviewer may ask how to Reverse a String in PHP without using strrev function or String reverse without using library function in php
There are few simple steps to answer them
- As you know, that string is a sequence of character, so that why it an array by default.
- we will declare a variable $i = 0 and run while until end of that string, find the length of string by incremented the value of $i
- will run another while loop, and start from max length of string, until it’s greater than equal to 0.
Let’s see an example
Reverse a String in PHP without using strrev function
<?php
$str = "This is string reverse logic without using any inbuild functions";
$rev = "";
$i = 0;
while(@$str[$i++] != NULL);
$i--;
while($i >= 0)
{
$rev = $rev.@$str[$i--];
}
echo "Original String : ".$str;
echo "<br><br>reverse String : ".$rev;
?>
Note: i have added @ because of PHP is not tightly coupled language, so it will throw notice. Because of @ it will stop showing notice.
Also Read,
- Reverse number in PHP without using function
- php interview questions and answers
- swap 2 variables without using third variable
Reverse a String in PHP using strrev function
<?php
$str = "This is string reverse using strrev functions";
echo "Original String : ".$str;
echo "<br><br>reverse String : ".strrev($str);
?>
Comments me below, if you need any help in this.