7

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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].