Tuesday, November 7, 2017

phpMyPassion

How To Reverse A String In PHP ?


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.

Image source : google images

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.

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.

For More Check Video:-




About Author -

Hi, I am Anil.

Welcome to my eponymous blog! I am passionate about PHP programming. Here you will find a hug of information on web development, web design, PHP and Latest technology.

Subscribe to this Blog via Email :