The associative array below represents different variables (identified by the key values) and their respective logical operators to compare with their neighbors - their neighbors being the variables below them.
Array(
[x] => or
[y] => and
[z] => or
[v] => null
)
I'm trying to figure out an algorithm that would take the data structure above and translate it to the following expression:
$result = lookup('x') || lookup('y') && lookup('z') || lookup('v');
Where lookup( $id )
is a function that looks up the boolean value of the given string $id
and returns it. So if x = true, y = true, z = false, and v = false, then the above would evaluate to:
$results = true || true && false || false; // should evaluate to true
This is what I have thus far:
$bool_vars = array( 'x' => 'or', 'y' => 'and', 'z' => 'or', 'v' => null);
$keys = array_keys( $bool_vars ); // Grab the variable identifiers
$result = lookup( $keys[0] ); // Get the bool value of the first variable
// If there is more than one var, we need to evaluate the boolean expression
if( count($keys) > 1 ){
foreach( $keys as $k => $key ){
// No need to evaluate the last element since it has no neighbor
if( $k + 1 == count( $keys ) ){ break; }
$operator = $bool_vars[ $key ]; // Get the logical operator to use
// Filter by operator
switch( $operator ){
case 'or':
// Get the bool value of the next var
$result = $result || isset( lookup( $keys[$k + 1] ) );
break;
case 'and':
$result = $result && isset( $lookup( $keys[$k + 1] ) );
break;
default:
continue;
}
}
}
return $result;
Just wanted another set of eyes on this to make sure the above makes sense - I've run this algorithm a number of times and it seemed like there were a few times where it didn't return the proper boolean value.