Skip to content
Advertisement

PHP WHILE statement iterating over array length

im learning some oop by watching some carts tutorials and im finding two different behaviors over what i think is the same thing, and i cant understand why: 1- the while stamennt should iterate while the condition its TRUE, but i see code only iterating accordingly to the length of an array provided as argument (which doesn’t make sense for me, but it does): here is the example:

while ($row = mysqli_fetch_assoc($result)){
                    
                    echo '<pre>'; print_r($row); echo '</pre>';
                    // component($row['product_name'], $row['product_price'], $row['product_image'], $row['id']);
                }

in the above case it only iterates 4 times cause that’s the length of the array.

but then i tried to replicate this to check it out

<?php
$test = ["nro1" =>1 , "nro2" => 2];
while ($test){
print_r($test); 
}

and its iterating forever, (that makes sense cause the array its always TRUE, independently from its length )

can someone shed some light on this for me please? thank you!

Advertisement

Answer

First case is not an array but a mysqli_result object. As the function is being called, it moves the internal pointer of the mysqli_result until it returns false. Second case you just loop the same variable, which will always evaluate to true. You can “emulate” the behavior with something like:

<?php
$test = ["nro1" =>1 , "nro2" => 2];

while ($item = current($test)) {
    print_r($item); 
    next($test);
}

or better yet:

<?php
$test = [1,2,3];

while ($item = current($test)) {
    echo $item;
    next($test);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement