sdot257
sdot257

Reputation: 10376

If statement doesn't seem to work correctly

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

Answers (7)

amir beygi
amir beygi

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

John Parker
John Parker

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

ChristopheD
ChristopheD

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

Corey Ballou
Corey Ballou

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

OneNerd
OneNerd

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

graphicdivine
graphicdivine

Reputation: 11231

You appear to be missing a closing }

Upvotes: 0

jspcal
jspcal

Reputation: 51944

try:

if ($range <= 50 ? $data <= $range : $data >= $range) {

}

or use an eval()

Upvotes: 5

Related Questions