A while loop usually has code that tries to avoid an infinite loop. I don't understand how this works while($row = mysqli_fetch_array($result_set)
? From the php manual, it says that mysqli_fetch_array returns an array per result row. So we are assigning here an array to the variable $row. Well I tried to replicate this:
$result_set = $database->query($sql);
while($row = mysqli_fetch_array($result_set)){
some code
}
with this:
$a = ["a","b","c"];
$num = 1;
while($row = $a){
echo $num;
$num++;
}
and I get an infinite loop. What am I missing?
In order to replicate the behavior of mysqli_fetch_array()
with an array you create consider the following: first create an array of arrays:
$a = ["a"=>array(1,2,3),"b"=>array(4,5,6),"c"=>array(7,8,9)];
$num = 1;
One way (there is more than one way to skin this proverbial cat) is to use a foreach()
loop to get and manipulate (echo) each row:
foreach($a AS $row){
echo $num ."
";
$num++;
echo $row[0] . " " . $row[1] . " " .$row[2] . "
";
}
This returns just what you would expect, your number followed by the data in each row of $a
example:
1
1 2 3
2
4 5 6
3
7 8 9
Once the loop has reached the end of the array it will exit, same as mysqli_fetch_array()
which essentially says, "foreach result_set as row".
You can try this with while
loop which is like while($row = mysqli_fetch_array($result_set))
$a = ["a","b","c"];
$num = 0;
while($num < count($a)){
echo $a[$num]."
";
$num++;
}