How To Set Default Value To A String In Php If Another String Is Empty?
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 'someEm
Solution 1:
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';
Solution 2:
$someString = (!isSet( $someEmptyString ) || empty( $someEmptyString ) )? "new text value" : $someEmptyString;
I think that would be the most correct way to do this. Check if that var is empty or if it's not set and run condition.
it's still a bit of code, but you shouldn't get any PHP warnings or errors when executed.
Solution 3:
Solution 4:
While ternary is more clear whats happening, You can also set the variable like this
($someString = $someEmptyString) || ($someString = "Default");
Works in all PHP versions, You can extend this to use more than 1 option failry easily also
($someString = $someEmptyString) ||
($someString = $someOtherEmptyString) ||
($someString = "Default");
which I personally find more readable than its ternary equivalent
Post a Comment for "How To Set Default Value To A String In Php If Another String Is Empty?"