0

I was looking into trying to revise some old code in an application that I work on. Currently the app parses out portions of a response string received from an API to determine if a request is good or if it failed. The response from the API sends back a string that contains the characters "DP" if the request was processed successfully. Right now there's a line of code in the app that is as follows:

if(stripos($result, "DP") !== false)

This is working fine now, but I can foresee an issue coming from this. stripos can return a "falsey" value even when the needle is in fact found within the haystack. Since the haystack string is zero-indexed with stripos the function will return 0 if the characters "DP" are found at the very beginning of the haystack string, which will incorrectly be read as false. This code is working now, but if for any reason the developers who maintain the API we work with decide to reformat their response, we will have problems. I was thinking of changing this to the following:

if(stristr($result, "DP") !== false)

From what I can tell this should be OK because according to php.net stristr only returns false if the needle is not found in haystack. I'm curious though if anybody has seen any problems similar to the one described above occurring with the stristr function.

morris295
  • 517
  • 1
  • 7
  • 21
  • according to this https://eval.in/101665 stripos with !== won't assume 0 is 'false' – Chris Feb 14 '14 at 15:25
  • possible duplicate of [Which method is preferred strstr or strpos?](http://stackoverflow.com/questions/5820586/which-method-is-preferred-strstr-or-strpos) – Alnitak Feb 14 '14 at 15:26
  • `!==` does not coerce, this is _exactly_ how you're supposed to use `stripos`. See also http://stackoverflow.com/questions/5820586/which-method-is-preferred-strstr-or-strpos/5820612#5820612 – Alnitak Feb 14 '14 at 15:26

3 Answers3

4

0 doesn't equal false if you use === (or !==).

See this fiddle for proof: http://phpfiddle.org/main/code/nih-esg

More info on the PHP site here: http://www.php.net/manual/en/language.operators.comparison.php

Grim...
  • 16,518
  • 7
  • 45
  • 61
0

Since your using !== it is a non issue, since the tripple operators checks both value and type

false != 0 : false

false !== 0 : true

Jesper Blaase
  • 2,320
  • 16
  • 13
0
<?php
    $result="DP";
    if (stripos($result, "DP") !== false)
    {
      echo stripos($result, "DP"); 
    }
?>

Returns 0 from within brackets.

Chris
  • 3,405
  • 4
  • 29
  • 34