Hallo! I have the following issue. An array with repeated items. How do I can number off duplicate elements. $arr = array ("a", "a", "b", "c", "c", "c", "d", "d"); foreach ($arr as $item) { echo "$item" . "<br>"; } PHP: I want the solution to be such a = 2; b = 1; c = 3; d = 2; I know the function array_count_values() PHP: , but it must arise by cycle foreach PHP: Thanks!
<? $uniques = array(); foreach ($arr AS $key => $value) { if (array_key_exists($key,$uniques)) { $uniques[$key] = $value + 1; } else { $uniques[$key] = 1; } } ?>
Thank you for quick replay coders! Haw work this script? $arr = array ("a", "a", "b", "c", "c", "c", "d", "d"); $uniques = array(); foreach ($arr as $key => $value) { if (array_key_exists($key,$uniques)) { $uniques[$key] = $value + 1; } else { $uniques[$key] = 1; } } PHP: If I test it, the result confusing me ....
it looks like keys and values are being confused in the last example. Try this: <?php $arr = array ("a", "a", "b", "c", "c", "c", "d", "d"); $uniques = array(); foreach ($arr as $key => $value) { if (array_key_exists($value,$uniques)) { $uniques[$value] += 1; } else { $uniques[$value] = 1; } } ?> PHP: In the array $arr, the letters are all values and not keys. Brew