Welcome to WebmasterWorld Guest from 54.167.46.29

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Assign multiple numeric values

Non consecutive numbers

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Aug 29, 2003
posts:944
votes: 0


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?

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

Senior Member

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

joined:Nov 12, 2005
posts:5966
votes: 0


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.

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Aug 29, 2003
posts:944
votes: 0


Thanks, that's exactly what I wanted.
11:55 pm on Sept 7, 2007 (gmt 0)

Senior Member

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

joined:Nov 12, 2005
posts:5966
votes: 0


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.
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members