0

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;
?>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Wajihurrehman
  • 567
  • 3
  • 15
  • 29

2 Answers2

0

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
Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
0

try this

$str = "Iam New Here";
$spaceCount = substr_count($str, " ");
$letterIndx = 0;
// count number of spaces and then loop
for($i=0; $i<=$spaceCount; $i++) {
  // get space positions
  $spaceIndx = strpos($str, " ", $letterIndx);
  // assign word by specifying start position and length
  if ($spaceIndx == 0) {
    $word = substr($str, $letterIndx);
  } else {
    $word = substr($str, $letterIndx, $spaceIndx - $letterIndx);
  }
  // push word into array
  $myArray[] = $word;
  // get first letter after space
  $letterIndx = $spaceIndx + 1;
}

// reverse the array
$reverse = array_reverse($myArray);

// echo it out
foreach($reverse as $rev) {
  echo $rev." ";
}

output will be : Here New Iam

Eka putra
  • 739
  • 10
  • 15