I have a series of if/elseif conditional statements using the same structure and syntax, and I'd like to clean up and condense the code within a foreach to more easily add and remove items as the list grows. What I'm starting with looks something like this:
if ( $condition1 == 1 && ( $condition2 == 1 || $condition3 == 1 ) ) {
$var = 'string 1';
} elseif ( $condition1 == 2 && ( $condition2 == 2 || $condition3 == 2 ) ) {
$var = 'string 2';
} elseif ( $condition1 == 3 && ( $condition2 == 3 || $condition3 == 3 ) ) {
$var = 'string 3';
} elseif ( $condition1 == 4 && ( $condition2 == 4 || $condition3 == 4 ) ) {
$var = 'string 4';
} else {
$var = 'default string';
}
Ideally, I would structure this more like:
$conditions = array(
'string 1' => 1,
'string 2' => 2,
'string 3' => 3,
'string 4' => 4,
);
foreach ( $conditions as $key => $value ) {
if ( $condition1 == $value && ( $condition2 == $value || $condition3 == $value ) )
$var = $key;
}
if ( empty($var) )
$var = 'default string';
The biggest issue here is that I want all if statements after the first iteration to be elseif to in case multiple conditions are met so I can control the hierarchy by the order of the items in the array. Also, this approach may be totally wrong and there could be a much better way to approach the problem altogether, so I'm open to any and all critique!