Array defaults if key does not exist?

If I have an array full of information, can I return values ​​by default if the key does not exist?

function items() { return array( 'one' => array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ), 'two' => array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ), 'three' => array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ), ); } 

And in my code

 $items = items(); echo $items['one']['a']; // 1 

But can I have a default value that will be returned if I give a key that does not exist, like,

 $items = items(); echo $items['four']['a']; // DOESN'T EXIST RETURN DEFAULT OF 99 
+37
arrays php default
Mar 04 2018-12-12T00:
source share
11 answers

I know this is an old question, but my google search on “php array defaults” took me here and I thought that posting the solution I was looking for would likely help someone else.

I need an array with default values ​​that can be overridden by user values. I ended up using array_merge .

Example:

 <?php $defaultOptions = array("color" => "red", "size" => 5, "text" => "Default text"); $customOptions = array("color" => "blue", "text" => "Custom text"); $options = array_merge($defaultOptions, $customOptions); print_r($options); ?> 

Outputs:

 Array ( [color] => blue [size] => 5 [text] => Custom text ) 
+68
Jul 03 '13 at 8:31
source share

Starting with PHP 7, there is a new operator specifically designed for these cases called the Null Coalesce Operator .

So now you can do:

 echo $items['four']['a'] ?? 99; 

instead

 echo isset($items['four']['a']) ? $items['four']['a'] : 99; 

There is another way to do this before PHP 7:

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

And the following will work without problems:

 echo get($item['four']['a'], 99); echo get($item['five'], ['a' => 1]); 

But note that when using this method, calling an array property for a value that is not an array will throw an error. for example

 echo get($item['one']['a']['b'], 99); // Throws: PHP warning: Cannot use a scalar value as an array on line 1 

In addition, there is a case when a fatal error will be issued:

 $a = "a"; echo get($a[0], "b"); // Throws: PHP Fatal error: Only variables can be passed by reference 

In the end, there is an unpleasant workaround, but it works almost well (in some cases, the problems described below occur):

 function get($value, $default = null) { return isset($value) ? $value : $default; } $a = [ 'a' => 'b', 'b' => 2 ]; echo get(@$a['a'], 'c'); // prints 'c' -- OK echo get(@$a['c'], 'd'); // prints 'd' -- OK echo get(@$a['a'][0], 'c'); // prints 'b' -- OK (but also maybe wrong - it depends) echo get(@$a['a'][1], 'c'); // prints NULL -- NOT OK echo get(@$a['a']['f'], 'c'); // prints 'b' -- NOT OK echo get(@$a['c'], 'd'); // prints 'd' -- OK echo get(@$a['c']['a'], 'd'); // prints 'd' -- OK echo get(@$a['b'][0], 'c'); // prints 'c' -- OK echo get(@$a['b']['f'], 'c'); // prints 'c' -- OK echo get(@$b, 'c'); // prints 'c' -- OK 
+45
Oct 29 '16 at 10:01
source share

This should do the trick:

 $value = isset($items['four']['a']) ? $items['four']['a'] : 99; 

A helper function would be useful if you need to write a lot:

 function arr_get($array, $key, $default = null){ return isset($array[$key]) ? $array[$key] : $default; } 
+19
Mar 04 2018-12-12T00:
source share

You can also do this:

 $value = $items['four']['a'] ?: 99; 

It means:

 $value = $items['four']['a'] ? $items['four']['a'] : 99; 

This eliminates the need to bind the entire instruction to a function!

Note that this does not return 99 if and only if the key 'a' not set to items['four'] . Instead, it returns 99 if and only if the value of $items['four']['a'] is false (either canceled or false, for example 0).

+4
Feb 27 '14 at 20:14
source share

Not that I knew.

You will need to check isset separately

 echo isset($items['four']['a']) ? $items['four']['a'] : 99; 
+3
Mar 04 2018-12-14T00:
source share

Use Array_Fill () Function

http://php.net/manual/en/function.array-fill.php

 $default = array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ); $arr = Array_Fill(1,3,$default); print_r($arr); 

This is the result:

 Array ( [1] => Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 ) [2] => Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 ) [3] => Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 ) ) 
+2
Jan 24 '15 at 9:52
source share

The question is very old, but maybe my solution is still useful. For projects where I very often need "if array_key_exists", for example, to parse Json, I developed the following function:

 function getArrayVal($arr, $path=null, $default=null) { if(is_null($path)) return $arr; $t=&$arr; foreach(explode('/', trim($path,'/')) As $p) { if(!array_key_exists($p,$t)) return $default; $t=&$t[$p]; } return $t; } 

Then you can simply “query” the array as:

 $res = getArrayVal($myArray,'companies/128/address/street'); 

This is easier to read than the equivalent old-fashioned way ...

 $res = (isset($myArray['companies'][128]['address']['street']) ? $myArray['companies'][128]['address']['street'] : null); 
+2
Jan 21 '16 at 16:34
source share

I don’t know how to do this exactly with the code that you specified, but you can bypass it using a function that takes any number of arguments and returns the desired parameter or default value.

Using:

 echo arr_value($items, 'four', 'a'); 

or

 echo arr_value($items, 'four', 'a', '1', '5'); 

Functions:

 function arr_value($arr, $dimension1, $dimension2, ...) { $default_value = 99; if (func_num_args() > 1) { $output = $arr; $args = func_gets_args(); for($i = 1; $i < func_num_args(); $i++) { $outout = isset($output[$args[$i]]) ? $output[$args[$i]] : $default_value; } } else { return $default_value; } return $output; } 
0
Mar 04 2018-12-12T00:
source share

You can use DefaultArray from the PHP Custom Library . You can create a new ItemArray from your elements:

 use function \nspl\ds\defaultarray; $items = defaultarray(function() { return defaultarray(99); }, $items); 

Or return DefaultArray from the items() function:

 function items() { return defaultarray(function() { return defaultarray(99); }, array( 'one' => array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ), 'two' => array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ), 'three' => array( 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, ), )); } 

Note that we create a default nested array with the anonymous function function() { return defaultarray(99); } function() { return defaultarray(99); } . Otherwise, the same instance of the array object will be used by default for all fields of the parent array.

0
Dec 18 '15 at 21:40
source share

In PHP7, as Slavik mentioned, you can use the null coalescing operator: ??

Link to PHP Docs .

-one
Dec 13 '16 at 11:41
source share

I think there is a better answer: is there a better way for PHP to get the default value of a key from an array (dictionary)?

i think i could be defined as a duplicate

-one
Dec 18 '18 at 12:58
source share



All Articles