Reputation: 899
I want to return a value based on the content of two variables. Let me explain better, I have three variables:
$var1 = 2; // This variable can change from 1 to 10 (based on the value in the database)
$var2 = 1; // This variable can have two values: 0 and 1 (based on the value in the database)
$result = ''; // This variable have a value based on the content of the two variables
I take two values from two different column of the Database ($var1 and $var2) and I have $result, a variable that have a value based on the content of $var1 and $var2
This can be done easily, making 20 conditions, like this:
if ($var1 == 1 && $var == 0) $result = 'good morning';
if ($var1 == 1 && $var == 1) $result = 'hello';
if ($var1 == 2 && $var == 0) $result = 'never';
But my question is: there is a way for write this piece of code more easily, easy to read and more manageable?
PS: $result have completely different values, concatenation not needed in this case.
Thanks.
Upvotes: 0
Views: 196
Reputation: 30893
Not sure if concat'ing this is what you're looking for. If it's not, then switch()
might be the way to go:
<?php
switch(true){
case ($var1 == 1 && $var == 0):
$result = 'value1.0';
break;
case ($var1 == 1 && $var == 1):
$result = 'value1.1';
break;
case ($var1 == 2 && $var == 0):
$result = 'value2.0'
break;
default:
$result = 'value0.0';
}
?>
Another options, after your edit, would be to make a Matrix:
$m = array();
$m[1] = array(0 => 'good morning', 1 => 'hello');
$m[2] = array(0 => 'never');
$result = isset($m[$var1][$var2])?$m[$var1][$var2]:""; // Or false if you prefer
Upvotes: 0
Reputation: 36964
All other answers are good, I just want to add another possibility:
Store your result
's values into an array, and call/search it like this:
$data[1][0] = 'good morning';
$data[1][1] = 'hello';
$data[2][0] = 'never';
//$data[x][y] = 'result of $var1=x and $var2=y';
// if exists a combination
if (isset($data[$var1][$var2])) {
// get the value
$result = $data[$var1][$var2];
}
Upvotes: 3
Reputation: 677
Well, many ways!
Following your piece of code you can build the string:
$result = "$var1" . "." . "$var2";
using the "value-to-string" effect.
You can also return an array:
$result = array("var1" => $var1, "var2" => $var2);
and access each part with $res["var1"/"var2"].
Upvotes: 0
Reputation: 324750
I think this might be a more manageable version of your code:
switch([$var1,$var2]) {
case [0,0]:
// code
break;
case [0,1]:
// code
break;
// ...
default:
// pairing wasn't defined
}
Without knowing the exact nature of $var1
and $var2
, nor the significance of $result
, I can't really help more, but this should be a good start.
Upvotes: 6