PHP | Reverse a String
Last Updated :
31 Dec, 2017
PHP serves us with many built-in methods which can be used to manipulate strings. In this article, we will learn about how to reverse a string using various methods available in PHP.
Examples:
Input : GeeksforGeeks
Output : skeeGrofskeeG
Input : 12485
Output : 58421
Below we have discussed about three basic and most commonly used methods of reversing strings in PHP:
-
Reversing string using strrev(): The strrev() function is a built-in function available in PHP and is used to reverse strings. This function takes a string as argument and returns a reversed string.
Syntax:
strrev($string)
Below is the implementation of program to reverse a string using strrev():
<?php
function Reverse( $str ){
return strrev ( $str );
}
$str = "GeeksforGeeks" ;
echo Reverse( $str )
?>
|
Output:
skeeGrofskeeG
-
Reversing string using recursion and substr(): We can also reverse a string using recursion and substr() function. The substr() function is used to get a substring of the original string. Here we have defined a function Reverse() with the string passed as argument. During every recursive call, we have used the substr() method to extract the first character of argument string and called the Reverse() function again by passing remaining part of string as argument and concatenated the first character at the end of the string returned from current call.
Below is the implementation of above idea:
<?php
function Reverse( $str ){
$len = strlen ( $str );
if ( $len == 1){
return $str ;
}
else {
$len --;
return Reverse( substr ( $str ,1, $len ))
. substr ( $str , 0, 1);
}
}
$str = "GeeksforGeeks" ;
print_r(Reverse( $str ));
?>
|
Output:
skeeGrofskeeG
-
In-place reversing a string without using library functions: In-place reversal of string means to reverse the string by doing modification in the original string itself and not making any copy of the original string. We can reverse a string in-place and without using any library function in PHP. The idea to do so is to traverse the original string from both sides, i.e. from both left and right until we reach the middle of the string. And keep swapping the characters while traversing. So, we will simply swap the characters, starting with the first and last, then second-first and second-last and so on, till we reach the middle of the string.
Below is the implementation of above idea:
<?php
function Reverse( $str ){
for ( $i = strlen ( $str )-1, $j =0; $j < $i ; $i --, $j ++)
{
$temp = $str [ $i ];
$str [ $i ] = $str [ $j ];
$str [ $j ] = $temp ;
}
return $str ;
}
$str = "GeeksforGeeks" ;
print_r(Reverse( $str ));
?>
|
Output:
skeeGrofskeeG
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...