Jump to content

Set variable based on another variable - CASE?


simonp

Recommended Posts

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.

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

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...

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";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.