A. Z.
A. Z.

Reputation: 736

PHP array with added variables

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

?>

Upvotes: 1

Views: 61

Answers (1)

nickb
nickb

Reputation: 59699

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);

Upvotes: 4

Related Questions