Andrew Cole Andrew Cole - 7 months ago 21
PHP Question

Empty line in foreach loop

Starting off I have looked at other answers and tried them but none resolve my issues. I have an empty result in a foreach loop. The code is:

<?php
$prices = explode(",", $products['price']);
$quantities = explode(",", $products['quantity']);
foreach($prices as $key => $val){
echo $val ." / ". $quantities[$key]."<br>";
}
?>


this give me this response:

$11.00 / 100 foot roll
30.00 / 250 foot roll
46.00 / 500 foot roll
79.00 / 1000 foot roll
/

You can see it at work here: https://abcole.me/monty/?shop&shop_id=117 The site is still under construction, but this is the last bug and I feel once this is fixed, I'll be able to use the same code for the drop downs.

Answer

You can try trimming the last ','. Like this:

<?php 
    $prices = explode(",", trim($products['price'], ', '));
    $quantities = explode(",", trim($products['quantity'], ', '));
    foreach($prices as $key => $val){
       echo $val ." / ". $quantities[$key]."<br>";
    }
?>
Comments