Question on arrays

Speaking as a beginner I would be very grateful for some basic discussion of arrays.

Specifically I was wondering why this works:


<?php

while ($row = mysqli_fetch_array($result))
{
$jokes[] = $row['joketext'];
}

?>

I get that it iterates through the array, but what’s the counter? how does it not just return the first array from $result over and over?

Sorry if this question is too basic for this forum.

[fphp]mysqli_fetch_array[/fphp] returns the next row in the result set each time it is called. When it reaches the end of the rowset it returns false, which breaks the while loop.

…because $jokes is an alternative means to add a new array item in PHP, as well as initialize a new array.

Read this manual page carefully and you will get it.

Especially this example:


<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

Left to fill in a new blank array (as in $jokes), PHP will start it with a numeric 0, and internally will make the next one 1 unless you tell it different.

Hm, I don’t think I have ever seen one in that category yet.

You are in the right place.

A good way to get a visualization is to,

$jokes = $row[‘joketext’];
echo $row[‘joketext’];

Each loop puts the text into the jokes array.

Hi robbo,

Welcome to sitepoint forums!

First of all, you can ask any basic or advanced questions at any time so no worries.

About your question:

I get that it iterates through the array, but what’s the counter?

I think this line should answer your question:

[fphp]mysqli_fetch_array[/fphp] returns the current row and sets the internal pointer to the next row.

.

That means you don’t have use any counter just to iterate the array in PHP. The example you are using is for mysql returned data. Even you can iterate the normal array without any counters with [fphp]foreach[/fphp] struct. For more details please visit the array or corresponding manual page for each functions.

I doubt that it returns the next row. I think [fphp]mysqli_fetch_array[/fphp] returns the current row (starting from 0 index) and sets the internal pointer to the next row.