Chris Yates
Chris Yates

Reputation: 243

PHP strpos not checking multiple items correctly

I am pulling in live prices via an api and am checking the CHANGEPCT24HOUR value.

If value is negative I want a down arrow, if it is positive would give a green up arrow.

The code below isnt working correctly. The current values are BTC : 8.32 & ETH : -2.86

Code:

      $json_string =    file_get_contents("https://myapi.com/?fsyms=BTC,ETH,DASH,LTC,NEO,XRP&tsyms=USD");
      $parsed_json = json_decode($json_string, true);
      $btcp = $parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
      $ethp = $parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];
      if(strpos($btcp,'-') == FALSE){ 
         $btc = "<i class=\"fa fa-fw fa-arrow-up\" style=\"color:green\"></i>".$parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
         } else {
         $btc = "<i class=\"fa fa-fw fa-arrow-down\" style=\"color:red\"></i>".$parsed_json['DISPLAY']['BTC']['USD']['CHANGEPCT24HOUR'];
         }
      if(strpos($ethp,'-') == FALSE){ 
         $eth = "<i class=\"fa fa-fw fa-arrow-up\" style=\"color:green\"></i>".$parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];
         } else {
         $eth = "<i class=\"fa fa-fw fa-arrow-down\" style=\"color:red\"></i>".$parsed_json['DISPLAY']['ETH']['USD']['CHANGEPCT24HOUR'];

         }
      $livechange = "BTC : ".$btc.'<br />';
      $livechange .= "ETH : ".$eth;
      echo $livechange;

It's showing an up arrow for both. However if I change the $eth strpos check to this if(strpos($ethp,'-') == FALSE) and then switch the order or the $eth around it works fine.

I don't know why the original strpos method won't work properly for the second check.

Upvotes: 1

Views: 67

Answers (1)

Steve Chamaillard
Steve Chamaillard

Reputation: 2339

You need to use === instead of == since strpos will return 0 if the character you looked for is in the first position of the string.

So in -50 :

strpos('-50', '-') == 0 == FALSE // This is true

strpos('-50', '-') === FALSE // This is false

Upvotes: 1

Related Questions