Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string in php without using any string function

Tags:

php

In yesterday Interview I was asked that how to reverse a string with out using any string function like strrev() or strlen(). I found this example on website but it gives error.is it possible to do this without strlen().

Uninitialized string offset: -1 in D:\xampp\htdocs\PhpProject1\index.php on line xx

$string = "ZEESHAN";

$i =0;

while(($string[$i])!=null){

        $i++;

}

$i--;

while(($string[$i])!=null){

        echo $string[$i];

$i--;

}
like image 382
Shakun Chaudhary Avatar asked Dec 14 '22 09:12

Shakun Chaudhary


2 Answers

$string = 'zeeshan';
$reverse = '';
$i = 0;
while(!empty($string[$i])){ 
      $reverse = $string[$i].$reverse; 
      $i++;
}
echo $reverse;
like image 153
Surace Avatar answered Dec 25 '22 11:12

Surace


Try -

$string = "ZEESHAN";

$j = 0;
while(!empty($string[$j])) {
   $j++;
}

for($i = ($j-1); $i >= 0; $i--) {
    echo $string[$i];
}

Output

NAHSEEZ
like image 42
Sougata Bose Avatar answered Dec 25 '22 11:12

Sougata Bose