Is there a better PHP way to get default values โ€‹โ€‹from an array (dictionary)?

In Python, you can do:

foo = {} assert foo.get('bar', 'baz') == 'baz' 

In PHP, you can use the ternary operator, for example:

 $foo = array(); assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz'); 

I am looking for a golf version. Can I make it shorter / better in PHP?

+43
arrays php default-value code-golf key
Jul 14 '11 at 16:09
source share
8 answers

I just came up with this little helper function:

 function get(&$var, $default=null) { return isset($var) ? $var : $default; } 

This not only works for dictionaries, but for all variables:

 $test = array('foo'=>'bar'); get($test['foo'],'nope'); // bar get($test['baz'],'nope'); // nope get($test['spam']['eggs'],'nope'); // nope get($undefined,'nope'); // nope 

Passing the previous undefined variable for each link does not raise a NOTICE error. Instead, passing $var by reference defines it and sets it to null . The default value will also be returned if the passed variable is null . Also note the implicitly generated array in the spam / egg example:

 json_encode($test); // {"foo":"bar","baz":null,"spam":{"eggs":null}} $undefined===null; // true (got defined by passing it to get) isset($undefined) // false get($undefined,'nope'); // nope 

Note that although $var is passed by reference, the result of get($var) will be a copy of $var , not a link. Hope this helps!

+44
Aug 08 '14 at
source share

Time goes by and PHP evolves. PHP now supports the coalescing zero operator , ?? :

 // 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'; 
+43
Dec 20 '16 at 16:09
source share

Use the error control operator @ with the short version of PHP 5.3 for the ternary operator:

 $bar = @$foo['bar'] ?: 'defaultvalue'; 
+18
Jun 23 '14 at 18:00
source share

PHP 5.3 has an abbreviated version of the ternary operator:

 $x = $foo ?: 'defaultvaluehere'; 

which is basically

 if (isset($foo)) { $x = $foo; else { $x = 'defaultvaluehere'; } 

Otherwise, no, there is no shorter method.

+7
Jul 14 '11 at 16:13
source share

It is useful for me to create such a function:

 function array_value($array, $key, $default_value = null) { return is_array($array) && array_key_exists($key, $array) ? $array[$key] : $default_value; } 

And use it as follows:

 $params = array('code' => 7777, 'name' => "Cloud Strife"); $code = array_value($params, 'code'); $name = array_value($params, 'name'); $weapon = array_value($params, 'weapon', "Buster Sword"); $materia = array_value($params, 'materia'); echo "{ code: $code, name: $name, weapon: $weapon, materia: $materia }"; 

The default value in this case is null , but you can configure it for everything you need.

Hope this is helpful.

+7
Mar 13 '14 at 19:50
source share

A โ€œlittleโ€ hacker way to do this:

 <?php $foo = array(); var_dump('baz' == $tmp = &$foo['bar']); $foo['bar'] = 'baz'; var_dump('baz' == $tmp = &$foo['bar']); 

http://codepad.viper-7.com/flXHCH

Obviously, this is not a good way to do this. But it is convenient in other situations. For example. I often declare shortcuts for GET and POST variables:

 <?php $name =& $_GET['name']; // instead of $name = isset($_GET['name']) ? $_GET['name'] : null; 

PS: You could call it the "built-in ==$_=& special comparison operator":

 <?php var_dump('baz' ==$_=& $foo['bar']); 

PPS: Well, you could just use

 <?php var_dump('baz' == @$foo['bar']); 

but this is even worse than the ==$_=& operator. You know, people donโ€™t like the error suppression operator.

+5
Jul 14 '11 at 16:19
source share

If you list the default values โ€‹โ€‹by key in the array, this can be done as follows:

 $foo = array('a' => 1, 'b' => 2); $defaults = array('b' => 55, 'c' => 44); $foo = array_merge($defaults, $foo); print_r($foo); 

Result:

 Array ( [b] => 2 [c] => 44 [a] => 1 ) 

The more key / value pairs that you list by default, the better the golf code becomes.

+2
Sep 23 2018-11-11T00:
source share

"Marc B" suggested a solution to use the ternary label $x = $foo?: 'defaultvaluehere'; but it still gives notifications. Perhaps this is a typo, maybe he meant ?? or it was written before the release of PHP 7. According to the triple description :

Starting with PHP 5.3, you can omit the middle part of the ternary operator. The expression expr1?: expr3 returns expr1 if expr1 evaluates to TRUE , and expr3 otherwise.

But it does not use isset inside and produces notifications. To avoid notifications, it is better to use Null Coalescing Operator ?? which uses isset inside it. Available in PHP 7.

The expression (expr1) (expr2) evaluates to expr2 if expr1 is NULL, and expr1 otherwise. In particular, this statement does not give a notification if the left value does not exist, as is isset (). This is especially useful for array keys.

Example # 5 Assigning a Default Value

 <?php // Example usage for: Null Coalesce Operator $action = $_POST['action'] ?? 'default'; // The above is identical to this if/else statement if (isset($_POST['action'])) { $action = $_POST['action']; } else { $action = 'default'; } ?> 
0
Mar 14 '19 at 6:55
source share



All Articles