Thursday, January 11, 2007

When the things are different from what they seem

In PHP, there is this handy feature called array_unique which creates an array of unique values, as the name indicates...

I sure was glad to see the function and decided to use it in my code while parsing some really big and dirty arrays...and sure enough, I had Unique values in the resulting Arrays...

here is how i used it -

$agency = array_unique($agency); //where agency is the array having the redundant values...
$count_agency = count($agency); //total number of distinct values
asort($agency); //to sort the values in acending order...

And sure enough, there was this little catch...-

The array preserved the location of the unique values...And I had the unique array with lots of null values...

There are two possible workarounds to this -

1. The quick and dirty way - Create a new array and use it
$count = 0;
foreach($agency as $var)
{
if($var!=NULL)
{
$new_agency[$count] = $var;
$count++;
}
}
$agency = $new_agency;
2. Use foreach in every calling of the array
Or you could just use foreach to loop through the array and use it that way...

But always remember, the comparison of any string to NULL in PHP is a bad idea. It not only slows your code down but also, leads to some false positives in matching the data.

So, the lesson for the day -
Clear the NULLs before you use the array_unique results.

Cheers

No comments: