note 87740 deleted from function.array-count-values by thiago
| From: | thiago@php.net | Date: | Fri, 20 Mar 2009 12:25:18 +0000 |
| Subject: | note 87740 deleted from function.array-count-values by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-152193@lists.php.net to get a copy of this message | ||
Note Submitter: psbauman
----
This doesn't seem to be documented, but it appears that array_count_values will write its key
values *back* to corresponding values in the argument array.
For example, say I have an array $id_numbers, consisting of 7 digits which contain leading zeros (so
number 1 would be 0000001 and so on). Most probably already know that array_count_values will
(lamely, IMO) strip the leading zeros and return the key as a number.
So if
<?php
$id_numbers[0] = 0056789;
$id_numbers[1] = 0012345;
$id_numbers[2] = 0012345;
// then
$id_counts = array_count_values($id_numbers); // will yield
$id_counts[56789] = 1;
$id_counts[12345] = 2;
/* That's not the weird part yet. If you dump $id_numbers you get an interesting result: */
$id_numbers[0] = 56789;
$id_numbers[1] = 12345;
$id_numbers[2] = 12345;
?>
Obviously quite nasty, if you aren't careful.
The way to prevent this is to encapsulate the argument array in the array_values() function:
$id_counts = array_count_values(array_values($id_numbers))
You'll still have the nagging problem that your $id_counts keys are still technically
incorrect, but depending on your program or incoming data, a sprintf() should rectify the stripping
of zeros (i.e. you basically have to make the array_count_values result a "temporary"
array, then loop through that, restore the zeros and populate a new "real" array with
correct keys)