Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Assign if not empty?

Tags:

php

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.

like image 506
Peter Avatar asked Jan 14 '11 22:01

Peter


People also ask

How do you check if a variable is not empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How check object is empty or not in PHP?

Using empty() won't work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared. Therefore you can use count() (if the object is Countable). Or by using get_object_vars() , e.g.

Is null or empty PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .


2 Answers

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); 
like image 123
Peter Avatar answered Oct 05 '22 16:10

Peter


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.

like image 24
BoltClock Avatar answered Oct 05 '22 17:10

BoltClock