Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default array values if key doesn't exist?

If I have an array full of information, is there any way I can a default for values to be returned if the key doesn't 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 to be returned if I give a key that doesn't exist like,

$items = items(); echo $items['four']['a']; // DOESN'T EXIST RETURN DEFAULT OF 99 
like image 609
cgwebprojects Avatar asked Mar 04 '12 14:03

cgwebprojects


People also ask

What is the default value of arrays?

When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.

What is Array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

Does an array key exist?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How do you replace a key in an array?

The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.


2 Answers

I know this is an old question, but my Google search for "php array default values" took me here, and I thought I would post the solution I was looking for, chances are it might help someone else.

I wanted an array with default option values that could be overridden by custom 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 ) 
like image 146
Hein Andre Grønnestad Avatar answered Oct 11 '22 15:10

Hein Andre Grønnestad


As of PHP 7, there is a new operator specifically designed for these cases, called Null Coalesce Operator.

So now you can do:

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

instead of

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

There is another way to do this prior the PHP 7:

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

And the following will work without an issue:

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

But note, that using this way, calling an array property on a non-array value, will throw an error. E.g.

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

Also, there is a case where a fatal error will be thrown:

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

At final, there is an ugly workaround, but works almost well (issues in some cases as described below):

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 
like image 31
Slavik Meltser Avatar answered Oct 11 '22 15:10

Slavik Meltser