Wajihurrehman Wajihurrehman - 3 months ago 8
PHP Question

getting error on reverse each word in php

i am tring to reverse string of each word here is my logic can any body check and make it right where i am getting wrong must be appreciated i know i am missing some thing little bit. must be appreciate if make this code and logic write.

code:-

<?php
$a = "i am getting late";
$count = 0;
$Reversestring = "";

while(isset($a[$count]))
{
if($a[$count] != '')
{
echo $a[$count];
$catchWord .= $a[$count];
$count++;
}else{
die($catchWord);
$Reversestring .= reverseWord($catchWord);
}
}

echo $Reversestring;

function reverseWord($word)
{
$revWord;
for($i = str_word_count($word) ; $i > 0; $i--)
{
$revWord = $word[$i];
}
return $revWord;
?>

Answer

The problem with your function is that you're adding the characters at the end of the new string. $str .= $foo appends $foo to the end of $str. You want to prepend it to actually reverse the string.

Using built-in functions

PHP already has built-in functions to achieve the task. Instead of modifying the function, you could simplify the logic and use the following solution. Why re-invent the wheel?

$result = array_map(function ($item) {
    return strrev($item);
}, explode(' ', $a));

$reversed = implode(' ', $result);

Without using built-in functions

If you do not want to use a built-in function, then you can use the following solution. Code is from this answer:

$reversed = "";
$tmp = "";

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

$reversed .= $tmp;

Output:

i ma gnitteg etal
Comments