Wajihurrehman Wajihurrehman - 1 year ago 62
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.


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

if($a[$count] != '')
echo $a[$count];
$catchWord .= $a[$count];
$Reversestring .= reverseWord($catchWord);

echo $Reversestring;

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

Answer Source

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 = "";
    $tmp = $string[$i] . $tmp;    

$reversed .= $tmp;


i ma gnitteg etal
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download