$items = explode(',',$product); // values is 4,2,4,2,2,4 $unique_items=array_unique($items); // gives me 4,2
What code should be next to give me 4 = 3 , 2 = 3 and store the number of values to a variable?
To count the duplicates in an array: Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
Storing Data in Arrays. Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
Yes, you do.
see: array_count_values
Like:
$occurences = array_count_values($items); print_r($occurences);
Output:
Array ( [4] => 3 [2] => 3 )
Usage:
echo $occurences[4]; // outputs 3
You're probably looking for array_count_values() function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With