Welcome to WebmasterWorld Guest from 50.17.74.162

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Assign multiple numeric values

Non consecutive numbers

     

abbeyvet

1:35 pm on Sep 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a form in one field of which users can choose one of several items. As an example let's say it is fruit they are choosing, apples, oranges, bananas, lemons etc.

I later need to assign a numeric value to their choice, but rather than doing multiple ifs

if($Fruit == "apples")
{
$FruitValue = 120;
}
elseif ($Fruit == "oranges")
{
$FruitValue = 80;
}
etc

is there a way to do this in one go, without all the ifs?

eelixduppy

1:38 pm on Sep 7, 2007 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member



You can have all the values in an array:

$fruit = array("apples" => 120, "oranges" => 80);
$FruitValue = $fruit[$Fruit];

You might want to check to see if the index exists in the array before you actually do what I have shown above, but this should work out a little better for you.

abbeyvet

2:03 pm on Sep 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks, that's exactly what I wanted.

eelixduppy

11:55 pm on Sep 7, 2007 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member



Just remember to use array_key_exists [us3.php.net] to check if the key is in there. If it isn't, then you should handle that situation appropriately.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month