Reputation: 33
I am checking around 20 variables like the following and I was wondering if there is a faster way (less lines) to do the same:
if ($data1 == 1) {
$res1 = "Yes";
} else {
$res1 = "No";
}
if ($data2 == 1) {
$res2 = "Yes";
} else {
$res2 = "No";
}
if ($data3 == 1) {
$res3 = "Yes";
} else {
$res3 = "No";
}
etc..
Upvotes: 0
Views: 86
Reputation: 31749
This should also work -
// number of variables to check
$num = 3;
// Loop for checking all the variables as per naming convnetions followed
for ($i = 1; $i <= $num; $i++) {
// set yes/no depending on the data set
${'res' . $i} = ${'data' . $i} == 1 ? 'yes' : 'no';
}
Upvotes: 1
Reputation: 6558
There are a few ways:
1) foreach loop:
$array = [$data1, $data2, $data3];
foreach ($array as $key => $value)
{
${'res'. $key} = ($value == 1 ? 'yes' : 'no');
}
Although as Qirel pointed out, this probably isn't the best thing to do. If you need to name new values $name. $x
then it's probably better as an array:
$array = [$data1, $data2, $data3];
$res = [];
foreach ($array as $key => $value)
{
$res[$key] = ($value == 1 ? 'yes' : 'no');
}
2) function:
function checkVal($value)
{
return ($value == 1 ? 'yes' : 'no');
}
$res1 = checkVal($data1);
3) ternary - not necessarily not repeating code, but it's shorter:
$res1 = ($data1 == 1 ? 'yes' : 'no')
$res2 = ($data2 == 1 ? 'yes' : 'no')
$res3 = ($data3 == 1 ? 'yes' : 'no')
Upvotes: 4
Reputation: 2363
I don't know the context but from what I can see my advice is to create an array of $data1, $data2, $dataN and loop all these values to create another array with all checks
$values = [$data1, $data2, $data3, $data4];
$responses = array_reduce($values, function ($a, $b) {
$a[] = 1 === $b;
return $a;
}, []);
Upvotes: 0