Search code examples
phparraysloops

while (next($array)) loop breaks prematurely on element with 0 value


I'm having a problem with pushing an object into an array.

Here's my object

Products Object
(
    [id] => 
    [title] => Titel
    [articlenumber] => Artikelnummer
    [price] => Prijs
    [sale_price] => Sale Prijs
    [description] => Tekst
    [views] => 1
    [brand] => Merk
    [soled] => 0
    [start_date] => 2011-04-21
    [end_date] => 2011-04-28
    [active] => 2
    [sale_text] => Sale Tekst
)

And here is my array I tryed to push everything to an array

Array
(
    [0] => title, Titel
    [1] => articlenumber, Artikelnummer
    [2] => price, Prijs
    [3] => sale_price, Sale Prijs
    [4] => description, Tekst
    [5] => views, 1
    [6] => brand, Merk
)

As you can see my code stops when he comes to the item "soled", it does it because the value is 0. When I put this value to something else if works fine.

Here is the code I'm using.

$value = array();
while (next($Product)) {
    $constant = key($Product);  
    array_push($value, $constant . ", " . $Product->$constant);         
    echo $constant . "<br>";
}

Solution

  • I don't know your exact needs, but its worth trying a simple cast to array.

    $value = (array) $Product;
    

    The problem with your cvrrent approach seems to be the zero evaluating to false, i think a strict compare should fix that.

        $value = array();
    
        while (next($Product) !== false) {
            $constant = key($Product);  
            array_push($value, $constant.", ".$Product->$constant);         
            echo $constant."<br>";
        }
    

    The foreach in the other answer is probably a better idea anyhow, but if you prefer the while loop for whatever reason you need to watch out for the comparison on that zero.