Click here to Skip to main content
15,662,426 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

How can I count the quantity of an array? Please see example. It is easier for me to explain through an example.

$_SESSION['products'] = array('123', '123', '456', '456', '456', '789', '789', '789', '789');

Display should be:
Item | Qty.
123  | 2
456  | 3
789  | 4 
Updated 5-Jan-15 19:00pm
Mohibur Rashid 6-Jan-15 0:40am    
Well, my strategy is
1. Copy the first number
2. memorize the copied number and count as 1
3. Then read the next number
4. Check my memory. If I have ever read that number
if I have:
4i) I would increase the count by 1 And then move to step 3
else(I haven't read)
4ii) Copy the number and move to Step 2

by the way, In php it would be far more easier.

1 solution

I'll make it rather easy for you, a trick that works particularly well with php and the fact that your array has numerical values to count.

The counting:
$countedStuff = NULL;
foreach($your_array as $a)
  $countedStuff[$a] = (isset($countedStuff[$a]))?$countedStuff[$a]+1:1;

PHP doesn't require you create each member [index] of the array - so you only need to create those that match your value. New indices get set to 1; older indices increment.

In php, this can even be done with alphanumeric values as indices.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900