0

I got an Error in my For Loop for some reason. I just want to go backwards through an array in php.

The Error in my Browser is:

Fatal error: Unsupported operand types in /var/html/modules/getChat.php on line 18

Line 18 in this Code part line 1:

Here is the Code:

for($x = sizeof($result-1); $x > 0; $x--)
{
    echo '<div class="message '.$result[$x].'"> <img src="'.$result[$x].'" /><span class="name">'.$result[$x].'</span>
    <p>'.$result[$x].'</p>
    </div>';
}

I hope you can help

Thanks

2
  • 2
    Really seems to be sizeof($result) - 1. Commented Feb 14, 2017 at 17:30
  • Thanks a lot i fixed it with sizeof($result) - 1 it was a stupid fault too Commented Feb 14, 2017 at 17:36

1 Answer 1

1

$result is an array, and substracting 1 from an array doesn't make any sense. You probably wanted to use this instead:

for ($x = sizeof($result) - 1; $x > 0; $x--) // ...

And yes, it seems that you unintentionally skip the very first element of your array here. If so, fix the condition ($x >= 0) - or just compact the whole loop into while:

$x = count($result);
while($x--) {
  // output with $result[$x]
}

If that's not a bottleneck (and most probably it's not), you better show the real intent of the code with array_reverse:

 foreach (array_reverse($result) as $el) {
    // output with $el
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Also x > 0 will not use first element of array. Maybe OP intends to do so, but still.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.