1

I have to write a lot of code like this:

         if ( !empty($value['fax'])) {
                $temp['fax'] = $value['fax'];
         } else {
            $temp['fax'] = "unknown";
         }

just wondering if there's a shorter version of this ...

3 Answers 3

3

Check out the Ternary Operator:

$temp['fax'] = (!empty($value['fax'])) ? $value['fax'] : 'unknown';

If you're actually checking isset() or is_null() and not empty() (which includes null, false, 0, '') then in PHP 7:

$temp['fax'] = $value['fax'] ?? 'unknown';
Sign up to request clarification or add additional context in comments.

2 Comments

You can't use ?: here like this, because if the condition is true it will use the returned value from !empty($value['fax']) which will be TRUE or FALSE and not the value of the variable.
Yeah, caught that. Bonehead mistake.
2

PHP7+ solution (Null coalesce operator):

$temp['fax'] = $value['fax'] ?? 'unknown';

Comments

1

Use the ternary operators:

$temp['fax'] = !empty($value['fax']) ? $value['fax'] : 'unknown'

2 Comments

I think you've mixed up the $temp with the $value.
Yep. Fixed. Thank you

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.