1

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";
}

?>

1 Answer 1

4

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 the foreach.

If you did a var_dump( $id['price']); before the loop, you'd see:

string(7) "11 3  6"

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:

$id = array("price" => array( "10"));

$id['price'][1] = $id['price'][0];
$id['price'][3] = ($id['price'][0] * 3 * 0.97);
$id['price'][6] = ($id['price'][0] * 6 * 0.95);

$id['price'][3] = round($id['price'][3],2);
$id['price'][6] = round($id['price'][6],2);
Sign up to request clarification or add additional context in comments.

1 Comment

Avoid weak typing: price => array("10")price => array(10).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.