1

Simple question but it comes up all the time ... what is the best way to check variables in PHP. Looking for opinions / advice. In examples below assume $pricing could be not defined, correctly defined as 'price', or incorrectly defined as array(), etc..

//Method A ?
echo (!empty($pricing) && (string) $pricing == 'price' ? 'selected="true"' : '');

//Method B ?
echo (isset($pricing) && $pricing == 'price' ? 'selected="true"' : '');

// Method C ?
/// your idea ?
Mike Q
  • 6,716
  • 5
  • 55
  • 62
  • `empty()` is generally better, except in this case it doesn't matter because you are setting it to an empty string anyways. – GrumpyCrouton Aug 08 '17 at 19:39
  • Possible duplicate of [What's the difference between 'isset()' and '!empty()' in PHP?](https://stackoverflow.com/questions/20582962/whats-the-difference-between-isset-and-empty-in-php) – GrumpyCrouton Aug 08 '17 at 19:45
  • @GrumpyCrouton I don't like to think so because I still want more clarity than just which of these to use (as I am not asking of outcomes). – Mike Q Aug 08 '17 at 20:21
  • The linked answer tells the difference between the 2 functions. – GrumpyCrouton Aug 08 '17 at 20:22

3 Answers3

4

Method C: don't handle $pricing being undefined or of the wrong type in this expression.

By the time you reach this expression in your code, you should have already verified that the variable you're going to use exists and checked its type, and thrown an exception if it isn't what it's supposed to be, whether you do that explicitly or through a type declaration in a method.

By casting it to a string, or ignoring it if it doesn't exist, you may be covering up a potential problem that should cause an exception. If it's not a string, then something went wrong earlier in your code that you need to fix.

So just let your expression do one thing instead of multiple things.

echo $pricing == 'price' ? 'selected="true"' : '';

Then, if you see undefined variable notices in your error log, go back and fix the problem at the source (i.e. the place where $pricing was defined or should have been.)

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • Well, I don't think RELYING on the warning's to debug seems like a good idea. You would most likely still need to trace the values anyway. Why not check for the correctness and output that problem or something right there ? like C++'s assert() etc.. ? – Mike Q Aug 08 '17 at 20:41
  • Yeah, If I understand you correctly, I think I agree, and.that's basically what I meant to say in the first part of the answer. I'm just saying, in my opinion that check should be done earlier, before you get to a point where you're ready to generate output. And using `empty` or `isset` like that won't do that check. It will just short-circuit the expression so `$pricing` isn't evaluated at all. – Don't Panic Aug 08 '17 at 20:54
1

If you're using PHP 7+, you have the null-coalesce operator (??) to compact the expression:

($pricing ?? '') === 'price' and print 'selected="true"';

Try it online at 3v4l.org.

Let's break that down:

  • ($pricing ?? '') gracefully handles the scenario where $pricing has not been defined. If defined, this expression returns the defined value of $pricing: otherwise, it returns the empty string ''.
  • === 'price' compares the now-defined value against exactly the value we are looking for. You can extend this test, of course. Like, if you had a set of defined values, you could instead use an in_array check.
  • and print 'selected="true"' reacts to the boolean result of the prior test, printing the desired value in the case of a match. Since outputting an empty string is equivalent to no output at all, we can simply use the and logical operator to conditionally output. Note that echo cannot be used here, as it's a language construct. Instead use print, printf, var_dump, etc.

That said, the emerging idiom for defaulting a potentially-undefined value uses the null-coalesce operator like:

$pricing = ($pricing ?? '');

I suggest defaulting in this way, versus the inline check given above, because it ensures $pricing is defined from that spot on. Said another way, don't litter your code with ($pricing ?? '') === 'price' checks: just do it once and be done with it.


As an aside, if you wanted to do multiple things on this condition, you could use an anonymous on-call:

($pricing ?? '') === 'price' and (function() {
    echo 'this';
    echo 'that';
})();

But I would not recommend these gymnastics.

bishop
  • 37,830
  • 11
  • 104
  • 139
0

I would write it this way:

echo (isset($pricing) && $pricing === 'price' ? 'selected="true"' : '');

This accomplishes the following:

  • condition evaluates to false if $pricing is undefined
  • condition evaluates to false if $pricing is not the same as 'price'

Finally, you are comparing with a specific value, anything other than that value will equate to false anyway, so checking for !empty() is redundant in this case.

Be sure to use the strict ( === ) comparison though, as if("some string" == 0) will return `true ( source ).

EDIT: Also, if you are unsure whether or not the variable has been defined (for example when working with $_POST), using isset() will save you a lot of trouble.

localheinz
  • 9,179
  • 2
  • 33
  • 44
William Perron
  • 1,288
  • 13
  • 18