note 126433 added to function.array-key-exists
| From: | johannes dot kingma at gmail dot com | Date: | Sat, 18 Sep 2021 10:21:00 +0000 |
| Subject: | note 126433 added to function.array-key-exists | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216970@lists.php.net to get a copy of this message | ||
I often need a value from an array and if missing, some default. So this became a staple in every
utils.php file I include in my projects:
<?php
/**
* get array value if key exist otherwise default
* @param string $key needle
* @param mixed[] $array haystack
* @param mixed $default value if needle not found
*/
function array_value($key, $array, $default = '')
{
if (array_key_exists($key, $array))
return $array[$key];
return $default;
}
?>
Works great for $_POST and $_GET or for some $option array that I send to function of class
constructor.
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 83.97.87.182)
----
Manual Page -- https://php.net/manual/en/function.array-key-exists.php
Edit -- https://main.php.net/note/edit/126433
Del: integrated -- https://main.php.net/note/delete/126433/integrated
Del: useless -- https://main.php.net/note/delete/126433/useless
Del: bad code -- https://main.php.net/note/delete/126433/bad+code
Del: spam -- https://main.php.net/note/delete/126433/spam
Del: non-english -- https://main.php.net/note/delete/126433/non-english
Del: in docs -- https://main.php.net/note/delete/126433/in+docs
Del: other reasons-- https://main.php.net/note/delete/126433
Reject -- https://main.php.net/note/reject/126433
Search -- https://main.php.net/manage/user-notes.php