Best example would be to show you how is this solved in Javascript:
var someString = someEmptyString || 'new text value';
In this javascript example, we have detected that 'someEmptyString' is empty and automatically set the value to 'new text value'. Is this possible in PHP and what's the shortest (code) way to do it?
This is how I do it now:
if ($someEmptyString == "")
$someString = 'new text value'; else $someString = $someEmptyString;
This is bugging me for quite some time and I would be very grateful if someone knows a better way to do this. Thank you!
is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .
When it comes to database columns, PHP's NULL has no place there. You see, SQL is a string based language. SQL's NULL must be represented by NULL with no quotes.
A variable is NULL if it has no value, and points to nowhere in memory. empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL .
You can use the ternary operator ?:
.
If you have PHP 5.3, this is very elegant:
$someString = $someEmptyString ?: 'new text value';
Before 5.3, it needs to be a bit more verbose:
$someString = $someEmptyString ? $someEmptyString : 'new text value';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With