1

I'm new to PHP and unfamiliar with the !== and === operators. Are Logic #1 and #2 below equivalent? And if not, why so? Basically, the code reads values from a csv row in a file, and if the value is empty it disregards empty or null values

//Logic #1
$value = readValue();
//skip empty values
if ( !$value || $value === '') {
   print "empty value found";
}else{
    doSomething();
}

//Logic #2
$value = readValue();
if ( $value && $value !== '' ) {
   doSomething();
}else{ //skip empty values
   print "empty value found";
}
Anthony
  • 36,459
  • 25
  • 97
  • 163
Les
  • 330
  • 5
  • 15
  • 1
    It would be better if you could try it with different values and types, just make a small script, loop through, find out. – ild flue Jan 25 '18 at 19:00
  • The second check in both `if`s is superfluous, as already implied by the first part of the condition. `!'' === true`. – trincot Jan 25 '18 at 19:02
  • I'm reading text from a file and the type comparison confuses me as to what I can do to test it, since it's just strings. – Les Jan 25 '18 at 19:05

1 Answers1

1

To answer your question about the == and === operators, those should be identical.

  • == is the opposite of !=
  • === is the opposite of !==

See this previous answer for more information on the difference between == and ===.


To improve your code a bit, I would suggest using the empty() function which will check for nulls and empty strings.

Something like this:

if (empty($value)) echo "nothing to see here";
else doSomething();
Ben Harris
  • 547
  • 3
  • 10