19
arrayextract
array_extract
SYNOPSIS
array_extract($arr, $keys)
DESCRIPTION
array_extract
returns an associative array of the elements from $arr
whose keys are listed in $keys
.
If $keys
is an associative array, the elements in the returned array are renamed with the values associated to the keys.
EXAMPLE
To extract a selection of values:
php > require 'library/dump.php';
php > require 'library/arrayextract.php';
php > $arr=array('name' => 'frasq', 'mail' => 'frasq@frasq.org', 'locale' => 'fr');
php > dump(array_extract($arr, array('name', 'mail', 'website')));
array(2) {
["name"] => string(5) "frasq"
["mail"] => string(15) "frasq@frasq.org"
}
To extract values while renaming the keys in the returned array:
php > dump(array_extract($arr, array('name' => 'username', 'mail' => 'usermail')));
array(3) {
["username"] => string(5) "frasq"
["usermail"] => string(15) "frasq@frasq.org"
}
CODE
- function array_extract($arr, $keys) {
- $r = array();
- foreach ($arr as $k => $v) {
- if (in_array($k, $keys)) {
- $r[$k] = $v;
- }
- else if (array_key_exists($k, $keys)) {
- $r[$keys[$k]] = $v;
- }
- }
- return $r;
- }
Comments