MDanz Posted October 28, 2010 Share Posted October 28, 2010 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. Link to comment https://forums.phpfreaks.com/topic/217139-php-loop-duplicate-help/ Share on other sites More sharing options...
Andy-H Posted October 28, 2010 Share Posted October 28, 2010 Sounds like a badly designed application to me, I assume you want to count the amount of duplicate individual values as you loop through as opposed to counting the number of duplicate values as a whole? Link to comment https://forums.phpfreaks.com/topic/217139-php-loop-duplicate-help/#findComment-1127729 Share on other sites More sharing options...
sharal Posted October 28, 2010 Share Posted October 28, 2010 You should probably use a multidimensional array for this, so that you could store the quantity, product name and eventually a price too probably, in the same array. For instance if your products comes from a database. This won't exactly solve your issue, this is merely another way of doing it and you will have to look other places for further instruction in building a shopping cart this way. <?php $items = array(); function addToCart($productId) { if(array_key_exists($productId, $items)) { // the product id is already in the array, increment the quantity $items[$productId]['quantity']++; } else { $items[$productId]['quantity'] = 1; } } ?> Link to comment https://forums.phpfreaks.com/topic/217139-php-loop-duplicate-help/#findComment-1127730 Share on other sites More sharing options...
Andy-H Posted October 28, 2010 Share Posted October 28, 2010 $quantity = array_count_values($items); $items = array_unique($items); foreach($items as $product): echo $product . ' <input type="text" size="2" value="' . $quantity[$product] . '" /><br />'; endforeach; EDIT: forgot array_unique. Link to comment https://forums.phpfreaks.com/topic/217139-php-loop-duplicate-help/#findComment-1127731 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.