note 22114 deleted from ref.array by sniper
| From: | sniper@php.net | Date: | Sat, 18 Oct 2003 18:04:45 +0000 |
| Subject: | note 22114 deleted from ref.array by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-58846@lists.php.net to get a copy of this message | ||
Note Submitter: bishop
----
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);