Quantcast
Channel: Interview Archives - Mydons
Viewing all articles
Browse latest Browse all 32

How to reverse a string in PHP without strrev(inbuilt) and Array function

$
0
0

php_logo_128

Reverse a string in PHP is pretty simple.  PHP provides inbuilt function to reverse a string PHP: strrev - Manual but knowing the logic of how it works is very simple and interesting. In the interview you may come across "Write a PHP function which should reverse the given string, condition u should not use strrev (inbuilt) function and array functions ".  You can answer this question with few steps,
  • Assign the given string to the variable
  • Calculate the length of the string
  • Declare a variable in which you have to store the reversed string
  • Iterate the string using for loop with appropriate looping and count
  • Concatenate the string inside the for loop
  • Display the reversed string.
The below code snippets shows the PHP code to reverse a sting without Array and strrev(inbuilt) function.
<?php 

$string = 'Mydons'; // string to be reversed
$string_length = strlen($string); // finding string length
$reversed_string = ''; // store the reversed string

for($i=$string_length;$i>-1;$i--){ // iterating to reverse the string

$reversed_string .= $string{$i};

}

echo 'The reversed string is <hr/>'.$reversed_string; // output will be 'snodyM'

?>
 

The post How to reverse a string in PHP without strrev(inbuilt) and Array function appeared first on Mydons.


Viewing all articles
Browse latest Browse all 32

Trending Articles