Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array help: array_count_values 2

Status
Not open for further replies.

monkey64

Technical User
Apr 27, 2008
69
GB
Okay, I'm a newbie. Apologies over to everyone who finds arrays easy...
I want to count all the values of an array. I'm using the function array_count_values.

Code:
$a = array('apple', 'bannana', 'pear', 'apple'); 
print_r(array_count_values($a));

// Gives Array ( [apple] => 2 [bannana] => 1 [pear] => 1 )

So good so far, but I want to concatenate a variable, so I need a foreach loop.

Code:
$a = array('apple', 'bannana', 'pear', 'apple'); 

foreach (array_count_values($a) as $value) {   
	$data .= $value . "*";
	$label .= $a[$value] . "*";
	} 
 
// $data gives me 211
// $label gives me pearbannanabannana

I need the following:

$data = apple, bannana, pear
$label = 2, 1, 1

somewhere my logic has gone to pot.
Can anyone put me on the right track?
 
Code:
$a = array('apple', 'bannana', 'pear', 'apple'); 
$v = array_count_values($a);
$labels = implode (',', array_keys($v));
$data = implode(',',array_values($v));
echo $labels;
echo '<br/>';
echo $data;
 
jpadie. Thanks for that fast response.
Now I see... You're using implode to return a string from the elements of the array. Easy when you know how.
Today I learnt something. Thanks again.
 
Jpadie,

You have answered a question I have been wondering for quite for several weeks.



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top