47

Is there any sort of assign-if-not-empty-otherwise-assign-null function in PHP?

I'm looking for a cleaner alternative to the following:

$variable = (!empty($item)) ? $item : NULL;

It would also be handy if I could specify the default value; for instance, sometimes I'd like ' ' instead of NULL.

I could write my own function, but is there a native solution?

Thanks!

EDIT: It should be noted that I'm trying to avoid a notice for undefined values.

3
  • 2
    !empty($item) && ($variable = $item); Commented Jan 14, 2011 at 22:05
  • @Delta: What happens to the default value then? Commented Jan 14, 2011 at 22:06
  • @Delta That doesn't work, it won't initialize $variable when $item is empty. Commented Jan 14, 2011 at 22:06

5 Answers 5

67

Update

PHP 7 adds the null coalescing operator to handle assignment depending on whether the right hand side is set.

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Additionally, PHP 7.4 adds the null coalescing assignment operator, which handles the opposite case -- assigning a value depending on whether the left hand side is set:

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
?>

Original Answer

I ended up just creating a function to solve the problem:

public function assignIfNotEmpty(&$item, $default)
{
    return (!empty($item)) ? $item : $default;
}

Note that $item is passed by reference to the function.

Usage example:

$variable = assignIfNotEmpty($item, $default);
Sign up to request clarification or add additional context in comments.

2 Comments

These two code fragments are not equal. assignIfNotEmpty(0, $default); will return $default while $username = 0 ?? 'nobody'; will return 0
@YourCommonSense it would probably work correctly if using isset instead of empty. The documentation also makes reference to isset. "In particular, this operator does not emit a notice or warning if the left-hand side value does not exist, just like isset()."
49

Re edit: unfortunately, both generate notices on undefined variables. You could counter that with @, I guess.

In PHP 5.3 you can do this:

$variable = $item ?: NULL;

Or you can do this (as meagar says):

$variable = $item ? $item : NULL;

Otherwise no, there isn't any other way.

6 Comments

I didn't know that about PHP 5.3. That certainly is cleaner!
Does this (?:) generates notice if undefined ?
Ish, I'd like to know this as well. That's what I'm trying to avoid.
@Ish Kumar: Unfortunately it does.
I guess $variable = @$item ?: NULL; would be nicer.
|
6

There's the null coalescing assignment operator (??=) that can be useful if you have a nullable parameter value and want to set a default if it's null.

function foo(?Bar $bar): void
{
    $bar ??= new Bar();
}

1 Comment

Available on PHP 7.4+
1

Well yes, there is a native solution for assigning the value or NULL when the variable was unset:

$variable = $possibly_unset_var;

If you just want to suppress the notice (which doesn't solve anything or makes the code cleaner), there is also a native syntax for that.

$variable = @$unset_var;

3 Comments

That's sort of a poor solution (the error suppression), don't you think?
@Peter: No, I don't think so. Notices are there for a reason, not as a pointless peeve.
It is poor. Php needs a warning-suppression operator really.
-1

I wouldn't recommend this on a production system, but:

<?php
//$value=1;
$item=@$value ?:null;
var_dump($item); // NULL
?>

<?php
$value=1;
$item=@$value ?:null;
var_dump($item); // 1
?>

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.