1

I can't seem to figure out how this loop works in PHP:

$people = array();
while($row = $result->fetch_assoc())
    $people[] = $row;

It seems as though the loop would just keep going, infinitely. But, it doesn't How exactly does this work? Can someone explain it to me step-by-step? I'm guessing that the while loop could also be written like this:

while(($row = $result->fetch_assoc()) == true)
10
  • Don't you need to specify a row name: $row = fetch_assoc()['my_row'] Commented Jan 9, 2014 at 2:36
  • @735Tesla normally I would, but I don't in this occasion, I need all of the rows written to an array. Commented Jan 9, 2014 at 2:38
  • so the variable $row is not actually referring to an individual row? Commented Jan 9, 2014 at 2:40
  • fetch_assoc returns NULL once it reaches end of data set. So no it is not an infinite loop. Commented Jan 9, 2014 at 2:40
  • 2
    @Hameed sorry I haven't been getting enough sleep lately. I was thinking about PDO but then I just realized PDO uses fetch() not fetch_assoc(). I thought something was off... Thank you for the correction. Commented Jan 9, 2014 at 9:02

3 Answers 3

3

The fetch_assoc fetches one result row at a time and stores it in $row. Since this is in a loop, you are fetching until you run out of rows

In the loop you are essentially pushing the $row value into a $people array

Sign up to request clarification or add additional context in comments.

Comments

1

Your code:

$people = array();
while($row = $result->fetch_assoc())
   $people[] = $row;

Example how its works (MySQL):

$people = array();
$result = mysql_query($query);
$rows_count = mysql_num_rows($result);
for ($i = $rows_count - 1; $i >= 0; $i--) {
   mysql_data_seek($result, $i);
   $people[] = mysql_fetch_assoc($result);
}

How U see first option is more compact.

Comments

1

fetch_assoc will return false either upon an error or when the cursor for the fetch hits the end of all the rows and no more rows can be fetched, so it will return false.

Every time you fetch for the query, a cursor keeps track of the last returned row and will continue to keep track ultimately till you finish reading all rows.

Edit: Sorry I was thinking about PDO and not mysqli, however it should be about the same thing.

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.