opposite of array_count_values

Discussion in 'PHP' started by dracula51, May 11, 2012.

  1. #1
    <?php
    $a=array("Cat","Dog","Horse","Dog");
    
    print_r(array_count_values($a));
    ?>
    PHP:
    it returns
    Array ( [Cat] => 1 [Dog] => 2 [Horse] => 1 )
    Code (markup):

    but i want exact opposite.
    i have an array like
    $b = array( [Cat] => 1 [Dog] => 2 [Horse] => 1 )
    PHP:
    but the i have to convert it like
    array("Cat","Dog","Horse","Dog")
    Code (markup):
    how can i do it? any array function ?
     
    dracula51, May 11, 2012 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
  3. akhileshbc

    akhileshbc Active Member

    Messages:
    98
    Likes Received:
    1
    Best Answers:
    5
    Trophy Points:
    75
    #3
    Try this:
    $b = array( "Cat" => 1, "Dog" => 2, "Horse" => 1 );
    
    $result = array();	// will hold the final contents
    foreach($b as $key => $value)
    {	
    	$t = array();
    	$t = array_fill(0, $value, $key);	// fill the array with a value for the given number of times
    	$result = array_merge((array)$result, (array)$t);	// merge this newly created array with the original one
    }	
    var_dump($result);
    PHP:
    Hope this helps :)
     
    akhileshbc, May 27, 2012 IP