Posted By

mthorn on 08/09/06


Tagged

php type


Versions (?)

Compare value _and_ type


 / Published in: PHP
 

URL: http://www.mthorn.net

Since PHP is typeless odd things can happen when a variable is not the type you expected. PHP treats 0, null, '0', false, and '' as false. Sometimes you really want to know if the value is false. The solution is simple, use the triple equal (===) operator.

  1. $value = '0';
  2.  
  3. // Here's how PHP works with the normal comparison operator:
  4. if ( $value )
  5. {
  6. // Since the $value is 0, PHP interprets it as false. However since
  7. // this is a non-empty string one might expect it to be true.
  8. print "if ( {$value} )\n";
  9. }
  10.  
  11. if ( $value == false )
  12. {
  13. // PHP automatically converts strings to numbers when it things it
  14. // needs to. This can cause problems because you may have wanted to
  15. // check for a boolean, not a string.
  16. print "if ( {$value} == false )\n";
  17. }
  18.  
  19. if ( $value == true )
  20. {
  21. // Since the value is both a string and numericaly 0, this evaluates
  22. // to false. I don't think there is any time when you would want it to
  23. // be true. Thankfully PHP doesn't think so either.
  24. print "if ( {$value} == true )\n";
  25. }
  26.  
  27. if ( $value == 0 )
  28. {
  29. // PHP will convert the value to the type you are comparing before
  30. // comparison. This may not be intented. However this evaluates
  31. // to true.
  32. print "if ( {$value} == 0 )\n";
  33. }
  34.  
  35. if ( $value == '0' )
  36. {
  37. // Since the value matches, this evaluates to true
  38. print "if ( {$value} == '0' )\n";
  39. }
  40.  
  41. // Now we try the === operator:
  42. if ( $value === 0 )
  43. {
  44. // Since the type of the value is not a number, this evaluates to false.
  45. print "if ( {$value} === 0 )\n";
  46. }
  47.  
  48. if ( $value === '0' )
  49. {
  50. // Since type _and_ value matches this evaluates to true.
  51. print "if ( {$value} === '0' )\n";
  52. }
  53.  
  54. // Some alternative ways to compare:
  55. if ( (int) $value === 0 )
  56. {
  57. // Since we typecast to an int, this works.
  58. print "if ( (int) {$value} === 0 )\n";
  59. }
  60.  
  61. if ( intval($value) === 0 )
  62. {
  63. // Intval takes the integer value of any string
  64. print "if ( intval({$value}) === 0 )\n";
  65. }
  66.  
  67. if ( (string) $value === '0' )
  68. {
  69. print "if ( (string) {$value} === '0' )\n";
  70. }
  71.  
  72. /*
  73.   The above outputs:
  74.  
  75.  
  76.   if ( 0 == false )
  77.   if ( 0 == 0 )
  78.   if ( 0 == '0' )
  79.   if ( 0 === '0' )
  80.   if ( (int) 0 === 0 )
  81.   if ( intval(0) === 0 )
  82.   if ( (string) 0 === '0' )
  83.   */

Report this snippet  

You need to login to post a comment.