Commonly in interview we have been asked about reverse a string. So here I am going to share the solution for this type of question with my article.
This is a basic question but most of the developers are stuck in it due to hesitation of interview. Interviewer only want to ask the main logic to reverse a string. He can either ask the function in php to reverse a string or also ask about procedural logic behind this.
Image source : google images
You can reverse a string using strrev() string function.
Syntax:
string strrev(string $string)
Output:
Return a string in reversed order.
So here are the commonly asked question with an example related to this.
#Reverse a string using PHP string function.
<?php
echo strrev("php is my passion"); //output:- noissap ym si php
?>
#Reverse a specific word in a string.
<?php
$string = "php is my passion";
$array = explode(" ", $string);
echo strrev($array[3]); //outpur:- noissap
?>
#Reverse a string without using string function.
<?php
$s = 'php is my passion';
$length = strlen($s);
for ($i = 0, $j = $length-1; $i < ($length / 2); $i++, $j--) {
$t = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $t;
}
echo $s; //Output:- noissap ym si php
?>
So using the above process you can reverse any type of string in PHP.
Note: Only a member of this blog may post a comment.