-1

I am trying to reverse a string without using strrev(). I thought this would be a simple task:

$str = 'I am a string';
$rev = '';

for($i = 0, $len = strlen($str), $j = $len -1; $i < $len; $i++, $j--) {
    $rev += $str[$j];
}

echo $rev;

Result is 0. Why is this?

When I do this:

$str = 'I am a string';
$rev = '';

for($i = 0, $len = strlen($str), $j = $len -1; $i < $len; $i++, $j--) {
    echo $str[$j];
}

I get: gnirts a ma I

Why is the second array returning the desired result but the first one is returning the wrong result, 0?

Robert
  • 10,126
  • 19
  • 78
  • 130

2 Answers2

1

You use . for concatenation and not + which is just for addition:

$rev .= $str[$j];
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
1

In php if you want to concatenate strings its the . operator, so instead of += you'll want a .=

Requisit
  • 64
  • 4