Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to reverse a string without using any php function..

user-image
Question added by Alok Kumar singh Rinku , Software Developer , www.rensoftglobal.com
Date Posted: 2013/09/18
Nouphal Muhammed
by Nouphal Muhammed , Senior Web Developer , Planet Green Solutions

If your question is to reverse a string with out using any built in function in PHP,  then i have created a class that would reverse the string for you. If your need is to reverse a string with out using PHP, then javascript is the answer. First i will provide with the PHP class.

 

 class Reverse_String{    

        private $i;    

        private $str;    

        private $output;     

        public function __construct($str){     

                 $this->str = $str;    

        }     

       private function getStringLength(){       

                   for($i=0;;$i++){      

                           if(!$this->str[$i]){          

                                  $this->i = $i-1;            

                                  throw new Exception('My Error.Just wanted to get the string length.');       

                            }           

                  }        

       }    

       public function reverseString(){            

           try{            

                $this->getStringLength();        

           } catch (Exception $e) {            

                       for($j=$this->i;$j>=0;$j--){                            

                              $this->output .= $this->str[$j];          

                        }            

                        return $this->output;        

          }        

       }

}

 

$rev = new Reverse_String('String to be reversed');

$str = $rev->reverseString();

echo $str;

 

Here we are looping the string with an infinite loop in getStringLength() function, and we create a custom exception. In reverseString() function we catch that exception. Now we have the string length. Now simply a reverse looping will do our job.  Hope my answer is suited to your question.

If  you need a javascript alternative, then i have answered it. please go to this link :

http://www.bayt.com/en/specialties/q/26811/26811/

 

Julfkar  Moh Umar
by Julfkar Moh Umar , Sr. Software Engineer , Aakash Edutech Private Limited

use simple mechanism as ::

$length=str_len($str);

 

for($i=$length -1;$i >=0;$i--)

{echo $str{$i};}

Louy Alakkad
by Louy Alakkad , Front End Developer , Alpha Apps

not possible

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.