PHP: Assign if not empty?

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.


Update

PHP 7 adds a new feature to handle this.

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';
?>

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);

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;

Tags:

Php