tags:

views:

68

answers:

5

Given the array below, can I do this for the switch(use the variable $cost inside the switch)?

Or does the switch($need a different variable here)

$cost=array(chocoru =>1, oeenergy =>0.35, lemondew =>0.55, chcmyst =>0.25, drsalty =>0.75);

Notice the $cost variable inside the switch is the same as the $cost associative array.

switch($cost)
{
case 1:
echo "You chose lemondew <br />";
echo "the price is".$cost["lemondew"]'<br>';
}
+1  A: 

No, you have to iterate over the array with a loop.

foreach($cost as $product => $price)
{
    echo "You chose " . $product . "<br />";
    echo "the price is" . $price . '<br>';
}
Ikke
Is is possible to create a conditional within the foreach?
Newb
Yes, it is. But you have to be aware of the for-case anti-pattern: http://en.wikipedia.org/wiki/Loop-switch_sequence
Ikke
A: 

It won't work. Variable in switch needs must be equal to any of case values for associated code to be executed.

Kamil Szot
A: 

A switch statement is a lot like a set of ifs. For example:

switch ($var) {
    case 1:
        $other_var = 6;
        break;
    case 2:
        $other_var = 3;
        break;
    case 3:
        $other_var = 2;
        break;
    default:
        $other_var = 0;
        break;
}

is logically equivalent to:

if ($var == 1) {
    $other_var = 6;
}
else if ($var == 2) {
    $other_var = 3;
}
else if ($var == 3) {
    $other_var = 2;
}
else {
    $other_var = 0;
}

You want to use a different construct based on what you're trying to do.

Samir Talwar
+1  A: 

You have a variable called $cost, which is an associative array mapping product names to their price. You can use the product name as array index, there is no need for any other variable or a switch statement:

echo "You chose $product <br />n";
echo "the price is " . $cost[$product] . "<br />n";
soulmerge
A: 
raceCh-