Thursday, August 11, 2011

how to reverse a string in php

This is just a simple question for fun. Well, it could be an interview question. Let's assume we are in an interview and being asked this question. The answers i can come up with are listed below:

$str = 'this is testing'; How to reverse the string to 'gnitset si siht'?

1. strrev, as long as we know this function exists.

$str = 'this is testing';
echo strrev($str);

2. What if we don't know this strrev function? Then this is not bad as well (i think):

$str               = 'this is testing';
$strArray       = str_split($str);
$reverseArray = array_reverse($strArray);
$reverseStr    = implode($reverseArray);

3. If we cannot remember any of these functions, we have to solve this problem by figuring out our own algorithm.

$str = 'this is testing';
$length = strlen($str);
$reverseStr = '';
for($i=$length-1; $i>=0; $i--) {
                $reverseStr .= $str[$i];

Oh yes, we can access a string's elements via array operator. It is not surprising if you know how C handles string.

4. What if we can't even remember strlen() either? Seriously? Ok, still not a problem:

$str = 'this is testing';
$reverseStr = '';
$i = 0;
while(isset($str[$i])) {
    $reverseStr = $str[$i] . $reverseStr;

As long as we know how PHP handles string internally(actually, how C handles string), we can solve the problem.

Frankly speaking, if i were asked this question in an interview, i could probably only come up with answer 3 and answer 4, cause I can't remember all those PHP functions either.

5. What if we can't even remember isset() function? You must be kidding. 

6. What if we can't figure out our own algorithm? humm... that is not good. If an interviewer ask you this question, he probably expect you can come up with your own solutions without using any special functions to see your capability to analyse and solve problems(Well, but i do see interview just trying to test candidates' memory). He probably even tells you that you cannot use any of those special functions. Anyway if we really cannot figure out any implementation,  I probably would just write down my ultimate answer/solution: Google

:D :D :D

No comments: