Count repetition in loop

Discussion in 'PHP' started by bumbar, Feb 8, 2008.

  1. #1
    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!
     
    bumbar, Feb 8, 2008 IP
  2. mvl

    mvl Peon

    Messages:
    147
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    why do you want to iterate when array_count_values() gives you the answer immediately?
     
    mvl, Feb 8, 2008 IP
  3. drewbe121212

    drewbe121212 Well-Known Member

    Messages:
    733
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    125
    #3
    <?
    $uniques = array();
    foreach ($arr AS $key => $value)
    {
    if (array_key_exists($key,$uniques))
    {
    $uniques[$key] = $value + 1;
    }
    else
    {
    $uniques[$key] = 1;
    }
    }

    ?>
     
    drewbe121212, Feb 8, 2008 IP
  4. bumbar

    bumbar Active Member

    Messages:
    68
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    91
    #4
    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 ....
     
    bumbar, Feb 9, 2008 IP
  5. Brewster

    Brewster Active Member

    Messages:
    489
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    60
    #5
    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
     
    Brewster, Feb 9, 2008 IP
  6. bumbar

    bumbar Active Member

    Messages:
    68
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    91
    #6
    Thanks! This work perfect ;)
     
    bumbar, Feb 9, 2008 IP