0

I'm trying to fetch data and display it via foreach loop but it's not working giving argument error but when i try this with while loop it's work fine. so my question is that why i cannot fetch data using mysqli_fetch_array with foreach why it's only possible with while loop

// While
while($row = mysqli_fetch_row($result))
{
    var_dump($row); echo "<hr />";  
}

// Foreach
foreach(mysqli_fetch_array($result) as $row)
{
    var_dump($row); echo "<hr />";
}
1
  • 1
    its different, while will continually invoke the the function, the foreach will not Commented Sep 23, 2016 at 6:55

2 Answers 2

1

You can't use foreach for mysqli_fetch_array directly. Foreach is a loop using for an exist array, to loop through each its item

You can use like below

$result = array();
    while($row = mysqli_fetch_array($result)) {
       $result[] = $row;
    }

    foreach($result as $row) {
        var_dump($row);
        echo "<hr />";
    }
Sign up to request clarification or add additional context in comments.

1 Comment

will using a reference; foreach(mysqli_fetch_array($result) as &$row) work?
0

Because mysqli_fetch_array as comes from it's name - fetches one row of your result as array.

So, foreach(mysqli_fetch_array($result) as $row) means

Fetch one row and iterate over this row.

While while($row = mysqli_fetch_row($result)) means

Do fetching rows until there's nothing to fetch. And when there's nothing to fetch while-condition is false and the loop breaks.

Info about while-loop and foreach-loop

Comments

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.