note 82388 deleted from function.list by googleguy
| From: | googleguy@php.net | Date: | Thu, 13 Sep 2012 10:03:31 +0000 |
| Subject: | note 82388 deleted from function.list by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190697@lists.php.net to get a copy of this message | ||
Note Submitter: tristan in oregon
----
Here's yet another way to make a list()-like construct for associative arrays. This one has the
advantage that it doesn't depend on the order of the keys, it only extracts the keys that you
specify, and only extracts them into the current scope instead of the global scope (which you can
still do, but at least here you have the option).
<?php
$arr = array("foo" => 1, "bar" => 2, "baz" => 3);
$keys = array("baz");
// $foo = 10;
$bar = 20;
$baz = 30;
extract(array_intersect_key($arr, $keys));
var_dump($foo);
var_dump($bar);
var_dump($baz);
?>
Should print
NULL
int(20)
int(3)
If your version of PHP doesn't have array_intersect_key() yet (below 5.1 I think), it's
easy to write a limited feature replacement for this purpose.
<?php
function my_array_intersect_key ($assoc, $keys)
{
$intersection = array();
foreach ($assoc as $key => $val)
if (in_array($key, $keys))
$intersection[$key] = $val;
return $intersection;
}
?>