simonp Posted April 30, 2015 Share Posted April 30, 2015 Hi, I want to set a variable based on the contents of another variable - I think I've see CASE used for this before but not entirely sure. Basically I'm trying to tidy this up: if ($var1 = "1") { $var2 = "a" } if ($var1 = "2" ) { $var2 = "b" } if ($var1 = "3") { $var2 = "c" } Any help appreciated. Thanks. Quote Link to comment Share on other sites More sharing options...
maxxd Posted April 30, 2015 Share Posted April 30, 2015 You want a switch statement. Basically: switch($var1){ case 1: $var2 = 'a'; break; case 2: $var2 = 'b'; break; case 3: $var2 = 'c'; break; } 1 Quote Link to comment Share on other sites More sharing options...
Solution cyberRobot Posted April 30, 2015 Solution Share Posted April 30, 2015 (edited) For what it's worth, you could also use if / elseif. More information, including examples, can be found here: http://php.net/manual/en/control-structures.elseif.php Note that you are using an assignment operator here: if ($var1 = "1") { As the code stands now, all three if tests will evaluate to true. Of course, you'll need to add the missing semi-colons after your $var2 statements for the code to even run. Edited April 30, 2015 by cyberRobot 1 Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted April 30, 2015 Share Posted April 30, 2015 (edited) because you are only mapping one value to another in a set of data, which is doing the same processing for each different value, just use a mapping/lookup array substitution - $map[1] = 'a'; $map[2] = 'b'; $map[3] = 'c'; $var2 = isset($map[$var1]) ? $map[$var1] : 'value not found'; conditional logic statements testing a value are for when you are doing different processing based on a value, such as creating/editing/deleting data... Edited April 30, 2015 by mac_gyver 1 Quote Link to comment Share on other sites More sharing options...
simonp Posted April 30, 2015 Author Share Posted April 30, 2015 (edited) Thanks folks. Apologies for the rookie coding errors - it's been a while I kept it simple and went with: // Assign plan_id if ($plan == "53") { $plan_id = "2"; } elseif ($plan == "54") { $plan_id = "3"; } elseif ($plan == "55") { $plan_id = "4"; } Edited April 30, 2015 by simonp Quote Link to comment Share on other sites More sharing options...
Muddy_Funster Posted April 30, 2015 Share Posted April 30, 2015 you may want to have a final else to catch any prospective errors, not everything goes to $plan... (sorry couldn't resist ) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.