6

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
  1. function array_extract($arr, $keys) {
  2.     $r = array();
  3.  
  4.     foreach ($arr as $k => $v) {
  5.         if (in_array($k, $keys)) {
  6.             $r[$k] = $v;
  7.         }
  8.         else if (array_key_exists($k, $keys)) {
  9.             $r[$keys[$k]] = $v;
  10.         }
  11.     }
  12.  
  13.     return $r;
  14. }

Comments

To add a comment, click here.