Reverse the string to get out as This is durga @ no. 1 position. Is below solution memory optimistic. How can we achieve the same without using a string function like i used strlen.

$string = "position 1 no. @ durga is This";

$reversed = "";
$tmp = "";
for ($i = 0; $i < strlen($string); $i++) {
    if ($string[$i] == " ") {
        $reversed .= $tmp . " ";
        $tmp = "";
    $tmp = $string[$i] . $tmp;
$reversed .= $tmp;

print strrev($reversed) . PHP_EOL;
  • 1
    \$\begingroup\$ This code seems to be an exact copy of this one: stackoverflow.com/a/2977638/1310566 without any attribution. Please don't copy other people's code here when you ask for a review. \$\endgroup\$ – Simon Forsberg Oct 26 '17 at 13:28

Your code looks quite complicated for the given task. I would suggest to use build-ins as it will increase readability and makes it easier to follow. There's also a performance boost.

The idea is:

  • split the string into word, using explode
  • reverse the resulting array, using array_reverse
  • concat the result, using implode

If you place everything in a handy function, it will look like this:

function reverseWords(string $string): string {
    $words = explode(' ', $string);
    $reversed = array_reverse($words);
    return implode(' ', $reversed);

print reverseWords("position 1 no. @ durga is This");

Which prints "This is durga @ no. 1 position".

Try it online. This is a test run on 3v4l.org with 100000 iterations to test both solutions performance-wise.


Not the answer you're looking for? Browse other questions tagged or ask your own question.