homepage Welcome to WebmasterWorld Guest from 107.20.25.215
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Assign multiple numeric values
Non consecutive numbers
abbeyvet




msg:3444025
 1:35 pm on Sep 7, 2007 (gmt 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?

 

eelixduppy




msg:3444028
 1:38 pm on Sep 7, 2007 (gmt 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.

abbeyvet




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

Thanks, that's exactly what I wanted.

eelixduppy




msg:3444604
 11:55 pm on Sep 7, 2007 (gmt 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.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved