note 82388 added to function.list
| From: | tristaninoregon at osu1 dot php dot net | Date: | Wed, 09 Apr 2008 02:44:55 +0000 |
| Subject: | note 82388 added to function.list | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-138043@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 216.92.131.65
Probable Submitter: 24.20.36.167
----
Manual Page -- http://www.php.net/manual/en/function.list.php
Edit -- https://master.php.net/note/edit/82388
Del: integrated -- https://master.php.net/note/delete/82388/integrated
Del: useless -- https://master.php.net/note/delete/82388/useless
Del: bad code -- https://master.php.net/note/delete/82388/bad+code
Del: spam -- https://master.php.net/note/delete/82388/spam
Del: non-english -- https://master.php.net/note/delete/82388/non-english
Del: in docs -- https://master.php.net/note/delete/82388/in+docs
Del: other reasons-- https://master.php.net/note/delete/82388
Reject -- https://master.php.net/note/reject/82388
Search -- https://master.php.net/manage/user-notes.php