An interesting if offbeat use for references: Creating an array with an arbitrary number of dimensions.
For example, a function that takes the result set from a database and produces a multidimensional array keyed according to one (or more) columns, which might be useful if you want your result set to be accessible in a hierarchial manner, or even if you just want your results keyed by the values of each row's primary/unique key fields.
<?php
function array_key_by($data, $keys, $dupl = false)
{
if (!is_array($data)) return null;
if (is_string($keys) or is_integer($keys)) $keys = Array($keys);
elseif (!is_array($keys)) return null;
$out = Array();
foreach($data as $cx => $row) if (is_array($row))
{
foreach($keys as $key)
{
$value = $row[$key];
if (!isset($last)) {
if (!isset($out[$value])) $out[$value] = Array();
$last =& $out; }
else {
if (!isset($last[$value])) $last[$value] = Array();
}
$last =& $last[$value];
}
if (isset($last))
{
if ($dupl) $last[$cx] = $row; else $last = $row; }
unset($last); }
else return NULL;
return $out;
}
$data = Array(Array('name' => 'row 1', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_a'),
Array('name' => 'row 2', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_b'),
Array('name' => 'row 3', 'foo' => 'foo_a', 'bar' => 'bar_b', 'baz' => 'baz_c'),
Array('name' => 'row 4', 'foo' => 'foo_b', 'bar' => 'bar_c', 'baz' => 'baz_d')
);
print_r(array_key_by($data, 'baz'));
print_r(array_key_by($data, Array('baz', 'bar')));
print_r(array_key_by($data, Array('baz', 'bar', 'foo')));
?>