19

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!

2

4 Answers 4

56

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';
Sign up to request clarification or add additional context in comments.

6 Comments

What happens with '0' here?
@Haozhun The condition fails. Truth table here.
Does this mean the answer contains a subtle bug?
@Haozhun Not sure if it's a bug. The falsiness of '0' is fairly standard PHP behaviour.
I'm not going to revise the answer, because it would render it pointless. You'd have to do empty($someEmptyString) ? 'new text value' : $someEmptyString, which is not very helpful code. But you make a good point which should be borne in mind if you're using this code.
|
5
$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.

1 Comment

3

You can use the ternary operator

$someString = $someEmptyString ?: "New Text Value";

Comments

0

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

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.