What is wrong with my code?
Warning: Invalid argument supplied for foreach() on line 12)
<?php
$id = array("price" => "10");
$id['price'][1] = $id['price'];
$id['price'][3] = ($id['price'] * 3 * 0.97);
$id['price'][6] = ($id['price'] * 6 * 0.95);
$id['price'][3] = round($id['price'][3],2);
$id['price'][6] = round($id['price'][6],2);
foreach($id['price'] as $money) {
echo '<option value="'.$money.'">.'.$money.'$</option>'."\n";
}
?>
You’re getting this error because
$id['price']is a string (as you defined it), and not an array.In PHP, you can access string indexes just the same as array indexes, so you’re setting individual characters of the string with the
$id['price'][x]assignments, and then trying to loop over the string in theforeach.If you did a
var_dump( $id['price']);before the loop, you’d see:If you want an array, and to have each assignment create a different element in the array, initialize
$id['price']to an array, and add elements appropriately: