2

I write a lot of if statements like this to check for an empty variable especially from mysql but is there an better/alternative syntax?

if($a!=""){

5 Answers 5

7

you can use empty() function

if(!empty($a)) {
Sign up to request clarification or add additional context in comments.

Comments

3

The fastest:

if ($a) { /* ... */ }

The funniest:

if (isset($a[0])) { /* ... */ }

3 Comments

what if ($a = 0)? OP need to check if the value is empty. Zero is not empty. The second one is better.
True. It depends what kind of values are possible in that variable.
empty produces the same results on "0"
1

Well syntax it is correct.

But " " is not empty so you could look at trim() for that.

I prefer the function strlen in combination with trim

if (strlen(trim($a))

If you prefer to be faster you could make your own function

function is_empty($string) {
  return (strlen(trim($string)) === 0);
}

3 Comments

as said " " is not an empty string, so empty will return false. Will the space is also empty (in most cases)
OH.. I see what you mean (blonde moment) I kept thinking yea a space isn't empty why are you rewriting the empty function!! I see what you mean now, good suggestion.
Checking the zero index is much more faster then strlen().
0

Or

!empty($a) ? (/* if not empty */) : (/* else */);

Comments

0

If you are just doing a one liner then you can use logical short circuting

$a && print ("Goodbye"); // same as $a != ""

or

$a || print ("Hello World"); // same as $a == ""

This leverages how PHP (and most languages) optimize binary operators

For the first case if $a results in a truthy value then the interpreter knows that it has to check the right hand side of the equation to determine the result of the expression.

If it is a falsey value then it wont evaluate the right hand side because it know's that it doesn't matter.

Similar logic is applied to the || statement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.