|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-05-11 17:07 UTC] mario dot dweller at seznam dot cz
Description: ------------ What about to create a new array function array_get? When we have a function like array_column... function array_get(array $array, $key, $default = null) Something like this. http://api.nette.org/2.0/source-Utils.Arrays.php.html#36-53 Ofc i can use that Arrays::get method or i can create my own function/static method. But it has a performance overhead for quite a common thing which should be as fast as it's possible. I hate typing this. isset($array['key1']['key2']) ? $array['key1']['key2'] : null; This looks better. array_get($array, ['key1', 'key2'], null) or just array_get($array, 'key') PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 07:00:01 2025 UTC |
In the case you have those keys in a variable like $keys = ['key1', 'key2'] you can access it only using a loop. That's one of the purpose of the function. BTW what looks better and what is more readable? $a = isset($array['a']) ? $array['a'] : null; $b = array_key_exists('b', $array) ? $array['b'] : 'default'; or $a = array_get($array, 'a'); $b = array_get($array, 'b', 'default'); ?And if null is considered as a valid value and the value is deep inside the array... $d = isset($array['a']['b']['c']) && array_key_exists('d', $array['a']['b']['c']) ? $array['a']['b']['c']['d'] : 'default'; or just array_get($array, ['a', 'b', 'c', 'd'], 'default');I don't know whether it's really appropriate for the framework to define this function.. surely it could be done faster in C but I'm sure this is fast enough: if (function_exists('array_get') === false) { function array_get($array, $key, $default) { return isset($array[$key]) ? $array[$key] : $default; } }