Reputation: 10376
I may be doing it wrong but take a peek. If I hardcode the logic, it works but not if I try to use it as a variable.
if($range <= 50) {
$operator = "<=";
} else {
$operator = ">=";
}
foreach($cursor as $s) {
$data = round($this->distance($zip_lat, $zip_lon, $s["lat"],$s["lon"]), 2);
if ($data .$operator. $range) {
$zipcodes[] = "$s[zipcode]";
}
}
I mean, I could add the if/else inside the foreach but wasn't sure if it adds any "overhead."
Upvotes: 0
Views: 289
Reputation: 1254
if ($data .$operator. $range)
Is always true, because it is a string ,not a null.
You can find out problem using this simple code:
$data="0";
$operator=">=";
$range="1";
if ($data .$operator. $range) {
echo $data .$operator. $range . " is true !";
}
Upvotes: 4
Reputation: 54445
I very much suspect that the if is simply evaluating the string $date.$operator.$range (which will always return true), as all you're doing is concatenating the operator and operands together.
As such, you may need to eval (duck and cover people, duck and cover) the contents of the if.
Upvotes: 1
Reputation: 116325
The 'dots' only do regular 'string' concatenation - you can't expect them (injected as strings) to behave like regular, 'real' operators.
Think about it: if $data = 'data1'
and $range = 50
your if statement becomes:
if ('data1<=50')
which will probably just evaluate to true or false, just as if ('yournamehere')
or if('randommumbojumbo')
Upvotes: 1
Reputation: 43547
You cannot have a variable representing an evaluation operator. You would have to switch your code to something like:
foreach ($cursor as $s) {
$data = round($this->distance($zip_lat, $zip_lon, $s["lat"],$s["lon"]), 2);
if ($range <= 50 && $data <= $range) {
$zipcodes[] = $s['zipcode'];
} else if ($data >= $range) {
$zipcodes[] = $s['zipcode'];
}
}
Upvotes: 0
Reputation: 6552
I think you are going to need to do this:
foreach ( $cursor as $s ) {
$data = round($this->distance($zip_lat, $zip_lon, $s["lat"],$s["lon"]), 2);
if ( $range <= 50 ) {
if ( $data <= $range ) {
$zipcodes[] = "$s[zipcode]";
}
} else {
if ( $data >= $range ) {
$zipcodes[] = "$s[zipcode]";
}
}
}
Upvotes: 0
Reputation: 51944
try:
if ($range <= 50 ? $data <= $range : $data >= $range) {
}
or use an eval()
Upvotes: 5