Muhammad Hamza Nisar
Muhammad Hamza Nisar

Reputation: 601

Mysqli_fetch_array not working for forearch loop

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 />";
}

Upvotes: 0

Views: 457

Answers (2)

vishal shah
vishal shah

Reputation: 316

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 />";
    }

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

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

Upvotes: 0

Related Questions