3

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
0

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.