I have a bit of dilemma, In PHP both foreach loop and while loop seem to do exactly the same thing in this situation:
foreach ($execute->result as $item) {
echo $item['user_pass'] . '<br />';
}
AND
while ($row = mysqli_fetch_assoc($execute->result)) {
echo $row['user_pass'] . '<br />';
}
- My question is are there any real differences?
- When would be better to use one over another or is it fine to use both?
- Does any of these two give you potential greater flexibility?
In this case they're exactly equivalent. The
mysqli_resultimplements theTraversableinterface (as documented here: http://www.php.net/mysqli_result ) so it can be iterated using aforeachloop as well.I suppose that, internally, calling
foreachon amysqli_resultobject performs the calls tomysqli_fetch_assocas well.I don't think it makes any difference to use the first method or the second; however, the first one looks prettier and "more PHP5" to me!
Speaking of flexibility, the first one is certainly more flexible as well, as you can use that code with any object that implements
Traversableand not justmysqli_result.