note 22114 added to ref.array
| From: | bishop@php.net | Date: | Fri, 07 Jun 2002 03:42:13 +0000 |
| Subject: | note 22114 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-31551@lists.php.net to get a copy of this message | ||
Sometimes you need an array that has all keys exactly equal to all values. For example, arrays that
look like:
array('a' => 'a', 'b' => 'b', 'c' =>
'c');
You can either do it manually (a pain for count($a) > 2), or use array_smear():
/* smear values across into keys, or vice-versa */
function array_smear($a, $v2k = true) {
$values = ($v2k) ? array_values($a) : array_keys($a);
$a = array();
foreach ($values as $v)
$a[$v] = $v;
return ($a);
}
array_smear takes an array, then a boolean specifying whether you want to smear the values over into
the keys (the default, and probably what you usually want) or vice-versa.
So:
$a = array('a', 'b', 'c');
$x = array_smear($a);
// x == array('a' => 'a', 'b' => 'b', 'c'
=> 'c');
$y = array_smear($a, false);
// y == array(0 => 0, 1 => 1, 2 => 2);
--
http://www.php.net/manual/en/ref.array.php
http://master.php.net/manage/user-notes.php?action=edit+22114
http://master.php.net/manage/user-notes.php?action=delete+22114
http://master.php.net/manage/user-notes.php?action=reject+22114