How do you get the top 10 items in an array (PHP)? - php

What is the best way to get the top 10 items in an array, I have an array that has several hundred items and I would like to get the top 10 items (most duplicated items) from the array using PHP, any suggestions?

This should do the trick:
$inputArray = array('orange','banana', 'banana', 'banana', 'pear', 'orange', 'apples','orange', 'grape', 'apple');
$countedArray = array_count_values($inputArray);
arsort($countedArray);
$topTen = array_slice($countedArray, 0, 10);
The above will return the array in order of the items with the most occurrences.

Try using php's array_count_values() to get the number of occurrences of each value in the array, in conjunction with arsort() to sort the array by the highest frequency values. Then you can take the top 10 most frequent values of the array with array_slice().
$dataArr = array('test', 4, 15.2, ...); // Input array with all data
$frequencies = array_count_values($dataArr);
arsort($frequencies); // Sort by the most frequent matches first.
$tenFrequencies = array_slice($frequencies, 0, 10, TRUE); // Only get the top 10 most frequent
$topTenValues = array_keys($tenFrequencies);
Note: We need to use array_keys() to get the final values because array_count_values() "returns an array using the values of the input array as keys and their frequency in input as values."

Related

Using php array_multisort twice to sort the same array

I have a large multidimensional array and I want to sort it twice by date using array_multisort and get the last 3 arrays from each sort
I could create a duplicate of the array but it seems a waste when all I want is 3 arrays from it
$rows = array(
array(...),
array(...),
...
);
I create the arrays to be sorted like this
foreach($rows as $key => $row) {
$submit_date[$key] = $row['Submit_Date'];
$view_date[$key] = $row['View_Date'];
}
On this iteration of the sort, everything works as I expect
array_multisort($view_date, SORT_DESC, $rows);
$viewed = array_slice(array_unique($rows, SORT_REGULAR), 0, 3, true);
but on this one which is run straight after, I get different results to what I expect
array_multisort($submit_date, SORT_DESC, $rows);
$unlisted = array_slice(array_unique($rows, SORT_REGULAR), 0, 3, true);
I can't sort on both sort arrays because there will be occasions where $view_date array will have null values.
Is there a way I can use the same array to sort by view date, get the last 3 rows then sort the array by submit date then get the last 3 rows?
It's because your first multisort messed up the order of $rows.
A dummy array should do the trick: $temp = $rows;

Getting the number of different values in a PHP array

I need to know the number of different values in an array. For example if it contains (5, 5, 5) then I should get 1. If it contains (4, 4, 2, 2) I should get 2. If (5, 5, 5, 5, 2, 2, 1, 5) then 3.
Is there a function that can achieve that directly in PHP?
echo count(array_unique($arr));
you can use array_unique which returns unique elements of array (result is also array type) and then count on result
Two simple ways to achieve that:
$diff_count = count(array_unique($input_arr));
$diff_count = count(array_flip($input_arr)); <-- recommended (performance)
array_unique() :
Removes duplicate values from an array - you can add adittional flags such as:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
array_flip():
Exchanges all keys with their associated values in an array - so duplicates keys are overwritten and you get a final array with the unique values as keys.
Flipping it twice will result in an array with unique values and the highest keys there were in the original input array.
More reading:
array_unique.
array_flip.
Benchmark:
Since the array_flip uses only O(n) exactly its much faster - using an array of 10,000 numbers as an input:
array_unique + count: ~28.615 ms.
array_flip + count: ~0.5012 ms. (winner)
Is there a function that can achieve that directly in PHP?
The closest one would be array_unique() but here is a simple function to achieve what you are looking for:
$arr = array(5,5,5,5,2,2,1,5);
function array_diff_values( $array ) {
return count( array_unique($array) );
}
$count = array_diff_values( $arr );
result of $count is 3

Ordering PHP arrays based on duplicate values

I have an array which contains duplicate values. I want to sort the array so that the values with the most duplicates appear first in line. Here's an example of my array:
array(1, 2, 3, 2, 1, 2, 2);
I want to sort this array so that it orders itself based on the amount of duplicates into the following:
array(2, 1, 3);
'2' has the most duplicates so it's sorted first, followed by values will less duplicates. Does anyone know how I can accomplish this?
$acv=array_count_values($array); // 1=>2, 2=>3,3=>1
arsort($acv); //save keys, 2=>3, 1=>2, 3=>1
$result=array_keys($acv); //get only keys 2,1,3
traverse the array, and increment OCCURENCES in another key-value associative array.
sort the second array by values.
get array_keys of second array.

Splitting an array equally:

I have the following array:
$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);
I want split it up into individual arrays so that each array contains seven or less values.
So for example the first array will become:
$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
$three = array(1,1,0,1,0,0,1);
$four = array(0,1);
Also how would you count the number of times 1 occurs in array one?
array_chunk() is what you are looking for.
$splitted = array_chunk($array, 7);
For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:
print array_sum($splitted[0]); // for the first chunk
I want split it up into individual arrays so that each array contains seven or less values.
Use array_chunk(), which is made expressly for this purpose.
Also how would you count the number of times 1 occurs in array one?
Use array_count_values().
$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);
// prints
Array
(
[0] => 3
[1] => 4
)
Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.
And as to your second question, try:
$num_ones=count(preg_grep(/^1$/,$array));

How to get the last n items in a PHP array as another array?

How to I get an array of the last n items of another array in PHP?
$n is equal to the number of items you want off the end.
$arr = array_slice($old_arr, -$n);
You can use array_slice:
$arr = array_slice($old_arr, -$n, $n, true);
If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag (4th parameter) set to true to avoid this.

Categories