0
foreach ($items as $product ) {
echo $product;
?><input type="text" size="2" value="<?php  
\\display quantity here
  ?>" name="quantity" /><?php
}

$items is an array. It has multiple values, some duplicate. How do i count the duplicate values in the array and display in this foreach loop?

i know array_count_values($product) but putting that in the foreach loop won't accomplish what i want.

another thing. i can get the foreach loop to not display duplicates by doing this

foreach (array_unique($items) as $product ) {
echo $product;
?><input type="text" size="2" value="<?php  
\\display quantity here
  ?>" name="quantity" /><?php
}

how would i accomplish both.

basically i want it to display the quantity without displaying duplicate rows. aka shopping cart.

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by cwarn23
0

I think you might need to do 2 loops. One to do the count, the second to display.

The first loop would go through & make a new array. The keys of this array would be the $product (I'm assuming it's a string), and the values would be the count. As you go through this loop, you check if this particular product has been encountered yet. If yes, increment it's associated value by one. If no, create it.

The second loop would then simply go through this new array, extracting the keys (product names) and values (product count).

If you control the SQL this information is being retrieved with, you can probably do all this in SQL.

1

Here is 2 examples of how to do it in the one script. Just delete the Option A section or the Option B section to view each example individually. As they both share the code at the top.

<?php
$items=array('apple','apple','poison','fruit','fruit','banana','veg','veg','veg','strawberry');
$count=array();
foreach($items AS $val) {
    if (!isset($count[$val])) {
        $count[$val]=1;
        } else {
        $count[$val]++;
        }
    }

    
    
    
    
//Above is required for both of below
////////////////////////////////////////////////
//Option A
    
foreach ($items as $product ) {
echo $product;
?><input type="text" size="2" value="<?php  
//display quantity here
echo $count[$product];
  ?>" name="quantity" /><?php
}

echo '<hr>';////////////////////////////////////
//Option B
foreach ($count as $product=>$counts ) {
echo $product;
?><input type="text" size="2" value="<?php  
//display quantity here
echo $counts;
  ?>" name="quantity" /><?php
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.