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!=""){
The fastest:
if ($a) { /* ... */ }
The funniest:
if (isset($a[0])) { /* ... */ }
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);
}
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