Reputation: 1216
I have an array with duplicate values.
I want print all items but also for duplicate value, I want print a number too.
Like this:
$arr = array('sara','jorj','sara','sara','jorj','eli','ana')
foreach($arr as $name)
{
echo $name;
}
How can print this result:
sara
jorj
sara-2
sara-3
jorj-2
eli
ana
Upvotes: 3
Views: 117
Reputation: 2995
Maybe Im little bit late to this answer, but heres my attempt
$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
$tmp = array();
foreach ($arr as $value) {
if (!isset($tmp[$value]) ) {
// if $value is not found in tmp array
// initialize the value in tmp array and set to 1
$tmp[$value] = 1;
echo $value;
}
else {
// found the value in tmp array
// add 1 to the value in tmp array
// output its current total count of this value
$tmp[$value] += 1;
echo "$value-", $tmp[$value];
}
echo "<br>";
}
output:
sara
jorj
sara-2
sara-3
jorj-2
eli
ana
This actually has the same output of array_count_values
, but broken into pieces of how it forms...I think
Upvotes: 2
Reputation: 59701
This should work for you:
Here I first use array_slice()
to get an array of all elements which are before the current element of the iteration, e.g.
iteration value | sliced array
-----------------------------------
sara | []
jorj | [sara]
Then I use this array with array_filter()
, to only keep the values with are equal to the current iteration value, so I can tell how many of the same values are in the array before the current value.
Now I simply have to count()
how many there are and if there are more than 1 we also print it in the output.
Code:
$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
foreach($arr as $key => $name) {
$count = count(array_filter(array_slice($arr, 0, $key), function($v)use($name){
return $v == $name;
})) + 1;
echo $name . ($count > 1 ? " - $count" : "") . PHP_EOL;
}
output:
sara
jorj
sara - 2
sara - 3
jorj - 2
eli
ana
Upvotes: 8