Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i count same values in an array and store it to a variable?

Tags:

arrays

loops

php

$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?

like image 455
yohdaman Avatar asked Jun 20 '11 07:06

yohdaman


People also ask

How do you count repeated values in an array?

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 .

How do you store array values in a variable?

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.

Can we store array in variable?

Yes, you do.


Video Answer


2 Answers

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 
like image 187
Yoshi Avatar answered Oct 16 '22 02:10

Yoshi


You're probably looking for array_count_values() function.

like image 41
duri Avatar answered Oct 16 '22 03:10

duri