note 87740 added to function.array-count-values
| From: | psbauman at osu1 dot php dot net | Date: | Thu, 18 Dec 2008 21:48:23 +0000 |
| Subject: | note 87740 added to function.array-count-values | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-148335@lists.php.net to get a copy of this message | ||
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
$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)
----
Server IP: 208.69.120.35
Probable Submitter: 128.114.64.10
----
Manual Page -- http://www.php.net/manual/en/function.array-count-values.php
Edit -- https://master.php.net/note/edit/87740
Del: integrated -- https://master.php.net/note/delete/87740/integrated
Del: useless -- https://master.php.net/note/delete/87740/useless
Del: bad code -- https://master.php.net/note/delete/87740/bad+code
Del: spam -- https://master.php.net/note/delete/87740/spam
Del: non-english -- https://master.php.net/note/delete/87740/non-english
Del: in docs -- https://master.php.net/note/delete/87740/in+docs
Del: other reasons-- https://master.php.net/note/delete/87740
Reject -- https://master.php.net/note/reject/87740
Search -- https://master.php.net/manage/user-notes.php