0

First sorry if you think the question is stupid but im new in php.., so the question is: Is it okay to use foreach loop instead of while loop?

Here is an example of what I have in mind:

foreach(mysqli_query($db_connect, 'SELECT * FROM exampletable') as $row)
{
    echo $row['exampleitem'];
}

It's working, but I'm not sure is it right, secure, slow and etc..

kpuc313
  • 15
  • 5
  • seems like a better use of foreach, they are basically the same. So if you find it easier to use one or the other for different examples you shouldnt worry. – Juan Diego May 24 '18 at 16:43
  • Thank you, for me is better, cuz it allows you to use query direct in "foreach" – kpuc313 May 24 '18 at 17:40

1 Answers1

3

Yes, this is OK. mysqli_query returns a mysqli_result object. The documentation says:

5.4.0 Iterator support was added, as mysqli_result now implements Traversable.

Barmar
  • 741,623
  • 53
  • 500
  • 612