niche Posted December 24, 2010 Share Posted December 24, 2010 I'm following a topic that talked about putting if statements into an array and checking them with in_array(). That's a new concept for me.Can you show me how to do that with this example script? <?php$a = 689;if ($a == 680) { $b = "Omaha"; } elseif ($a == 685) { $b = "Lincoln"; } elseif ($a == 689) { $b = "Hastings"; }echo $b;?> Link to comment Share on other sites More sharing options...
gar onn Posted December 24, 2010 Share Posted December 24, 2010 I guess you need: switch <?phpswitch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break;}?> Merry x-mas Link to comment Share on other sites More sharing options...
niche Posted December 24, 2010 Author Share Posted December 24, 2010 Thanks, but I don't think that's the answer. Shouldn't the answer have an array in it and use in_array()? Link to comment Share on other sites More sharing options...
boen_robot Posted December 24, 2010 Share Posted December 24, 2010 Your example is a little more complicated than the topic I'm assuming you're talking about, because you need to have one value be assigned based on another value, whereas in that example, it was the same value, as long as it's in the list.There are a few ways to deal with this, but the easiest is probably to have two arrays - one with the possible values (of $a), and another with the corresponding assignments (to $ for each possible value. If the value is in the array of acceptable values, get the array value with the same key: <?php$a = 689;$correspondingValuesForB = array(680 => "Obama", 685 => "Lincoln", 689 => "Hastings");$possibleValuesOfA = array_keys($correspondingValuesForB);/* That's equavalent to manually writing array(680, 685, 689) */if (in_array($a, $possibleValuesOfA)) {$b = $correspondingValuesForB[$a];}else {/* OK, why do you people keep forgetting to define what happens on failure? */}echo $b;?> See in_array() if you haven't already. Link to comment Share on other sites More sharing options...
niche Posted December 24, 2010 Author Share Posted December 24, 2010 Thanks boen_robot for showing me. I would've tried doing it another way.Also thanks for weighing-in gar onn. Link to comment Share on other sites More sharing options...
Fmdpa Posted December 26, 2010 Share Posted December 26, 2010 Boen_robot, it was Ohama, not Obama: the city, not the person. Link to comment Share on other sites More sharing options...
boen_robot Posted December 26, 2010 Share Posted December 26, 2010 Boen_robot, it was Ohama, not Obama: the city, not the person. Oh yeah . Omaha the city (not Ohama, the pirate ) indeed.Well, mr. Lincoln fooled me, coupled with the fact I don't know all american presidents and Hastings sounds like a good name for one . Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.