I have an expression which looks like this:
$condition = "$foo>$bar";
and an array which has the values for the expression elements:
array(
'foo' => 3,
'bar' => 4
)
I did the replacement, in the $condition
string using the str_replace()
function, but the 3>4
expression returns true.
How can I properly evaluate my $condition
expression in a if()
statement?
I have no idea why you'd want to do this, but this is technically possible. Use extract()
to import the variables from the array into the current scope. Once you have the variables, you can simply compare them as usual:
$values =array(
'foo' => 3,
'bar' => 4
);
extract($values);
$result = $foo > $bar;
if ($result) {
echo '$foo is greater than $bar';
} else {
echo '$foo is not greater than $bar';
}
If $condition
is a string and you can't change it, you could use eval()
to evaluate the expression first:
$condition = "$foo>$bar";
eval(sprintf('$result = %s;', $condition));
if ($result) {
echo '$foo is greater than $bar';
} else {
echo '$foo is not greater than $bar';
}
If the values "foo" abd "bar" are in an array and can either be strings or integers then why not use array sorting functions to evaluate this way:
<?php
$values =array(
'foo' => 'mary and john',
'bar' => 'john and mary'
);
/**
* This sorts the arrays by ascending order *
* Result: Array ( [bar] => 2 [foo] => 5 ) *
*/
natsort($values);
/**
* now run the condition
* To do this we check the first key, which naturally is the smallest key
* Alternatively, we could also check the last key, the higher value
*/
$keys=array_keys($values);
$lower_key=reset($keys);
$higher_value=end($keys);
if($lower_key=='foo'){
echo 'Foo <strong>('.$values['foo'].')</strong> is less tha Bar <strong>('.$values['bar'].')</strong>';
}
else{
echo 'Foo <strong>('.$values['foo'].')</strong> is greater than Bar <strong>('.$values['bar'].')</strong>';
}
/**
* This can be summarized as
*/
natsort($values);
if(reset(array_keys($values))=='foo'){
echo 'Foo <strong>('.$values['foo'].')</strong> is less tha Bar <strong>('.$values['bar'].')</strong>';
}
else{
echo 'Foo <strong>('.$values['foo'].')</strong> is greater than Bar <strong>('.$values['bar'].')</strong>';
}
//Foo (mary and john) is greater than Bar (john and mary)
?>