zodehala
03-10-2010, 01:35 PM
wh doesnot it run folllowing $value?
whare is wrong ?
$i=3;
if($i = 1){$value = "a";}
elseif($i = 2){$value = "b";}
elseif($i = 3){$value = "c";}
elseif($i = 4){$value = "d";}
elseif($i = 5){$value = "e";}
echo $value ;
You need to compare the values with "==" instead of assigning with "=" (which, also returns the value you set)
i.e.
$i=3;
if ($i == 1) {$value = "a";}
elseif ($i == 2) {$value = "b";}
elseif ($i == 3) {$value = "c";}
elseif ($i == 4) {$value = "d";}
elseif ($i == 5) {$value = "e";}
echo $value;
It might be a bit prettier if you did:
$i=3;
switch ($i) {
case 1:
$value = "a";
break;
case 2:
$value = "b";
break;
case 3:
$value = "c";
break;
case 4:
$value = "d";
break;
case 5:
$value = "e";
break;
default:
echo 'Unknown value for $i';
}
echo $value;
-- but don't forget the "break"s!
zodehala
03-10-2010, 02:17 PM
You need to compare the values with "==" instead of assigning with "=" (which, also returns the value you set)
i.e.
$i=3;
if ($i == 1) {$value = "a";}
elseif ($i == 2) {$value = "b";}
elseif ($i == 3) {$value = "c";}
elseif ($i == 4) {$value = "d";}
elseif ($i == 5) {$value = "e";}
echo $value;
It might be a bit prettier if you did:
$i=3;
switch ($i) {
case 1:
$value = "a";
break;
case 2:
$value = "b";
break;
case 3:
$value = "c";
break;
case 4:
$value = "d";
break;
case 5:
$value = "e";
break;
default:
echo 'Unknown value for $i';
}
echo $value;
-- but don't forget the "break"s!
is it possible to do it using ternary operator?
is it possible to do it using ternary operator?
Anything's possible: $i = 3;
$value = ($i == 1) ? "a" : (
($i == 2) ? "b" : (
($i == 3) ? "c" : (
($i == 4) ? "d" : (
($i == 5) ? "e" : (
'Unknown value for $i')))));
echo $value; ... though not necessarily desirable ;)
I'm not a fan of using a ternary "if" in this case as it's pretty unreadable: this is the sort of tactic used to obfuscate code!