Associative Array (Hash) Tricks in PHP

Suppose you're tallying some data. You want to know if a value has shown up in the data. You can do this by using the array, like this:

$tally = array();
while( $row = getData() )
    array_push($tally, $row);
if (in_array($tally, 'theValueIWant'))
    echo "yes";
else
    echo "no";

There's a faster way, by using the array key. (It should be faster.)

while( $tally[ getData() ] = 1 ) { }
if ($tally['theValueIWant'])
    echo "yes";
else
    echo "no";

We're taking advantage of the hashing feature. This technique is widely used in Perl.

The associative array (hash) is a sophisticated data structure. Think of it as a rapid search table. That's what it is, after all.

To make it even shorter, you can use the ternary operator:

while( $tally[ getData() ] = 1 ) { }
echo $tally['theValueIWant'] ? 'yes' : 'no';

Another trick is to get a list of values, with duplicates removed:

while( $tally[ getData() ] = 1 ) { }
$result = array_keys($tally);

There you go. No sorts, comparisons, or anything like that. You just load the data into the keys, and duplicate values are eliminated.

Here's how to get the histogram of the data. That's the number of times a data value occurs.

while( $tally[ getData() ]++ ) { }
print_r(ksort($tally));