Jump to content

Set variable based on another variable - CASE?

Go to solution Solved by cyberRobot,

Recommended Posts



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.



Link to comment
Share on other sites

  • Solution

For what it's worth, you could also use if / elseif. More information, including examples, can be found here:



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.  :happy-04:

Edited by cyberRobot
  • Like 1
Link to comment
Share on other sites

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 by mac_gyver
  • Like 1
Link to comment
Share on other sites

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 by simonp
Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.