简体   繁体   中英

Finding array with highest and lowest number of elements

I would like to figure out which array is the biggest and the smallest according to the number of values it contains.

For example:

$array=[
 "subarray1"=>[1]
 "subarray2"=>[1,2,3,4,5,6,7,8]
 "subarray3"=>[1,2,3,4]
];

max_elements($array) returns subarray2 and min_elements($array) returns subarray1

Does PHP have any functions that can select array with most number of elements and the array with the least number elements?

iterate once getting the count , then return the key with array_search using min or max

<?php

function extreme_elements($arr, $min_max){

  foreach ($arr as $key => $val)
    $arr[$key] = count($val);

  return array_search($min_max($arr),$arr);

}

// friendly named wrappers
function max_elements($arr){
  return extreme_elements($arr, 'max');
}
function min_elements($arr){
  return extreme_elements($arr, 'min');
}

$array=[
 "subarray1"=>[1],
 "subarray2"=>[1,2,3,4,5,6,7,8],
 "subarray3"=>[1,2,3,4]
];

echo max_elements($array); // subarray2
echo min_elements($array); // subarray1

An example of finding the keys for the sub-arrays that contain the least members:

<?php
$array=[
 'subarray1'=>[1],
 'subarray2'=>[1,2,3,4,5,6,7,8],
 'subarray3'=>[1,2,3,4],
 'subarray4'=>[3],
];

$counted = array_map('count', $array);
$min_member_count = min($counted);
$mins = array_filter($counted, function($item) use ($min_member_count) {
    if($min_member_count == $item) return true;
});
var_export(array_keys($mins));

Output:

array (
  0 => 'subarray1',
  1 => 'subarray4',
)

Inspired by @Rizier123's comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM