如何比较PHP中的两个数组并找出哪两个数组中的元素比另一个多?我怎样才能找出2个数组中有哪些元素更多?
例如,我有数组
$a = array(2,3,4);
$b = array(1,2,3,4,5,6,7);
我将如何能够动态地返回the array $b
因为它有更多的元素?有没有PHP中的内置函数呢?
如何比较PHP中的两个数组并找出哪两个数组中的元素比另一个多?我怎样才能找出2个数组中有哪些元素更多?
例如,我有数组
$a = array(2,3,4);
$b = array(1,2,3,4,5,6,7);
我将如何能够动态地返回the array $b
因为它有更多的元素?有没有PHP中的内置函数呢?
要回答这个问题“我怎么会是能够动态地返回......”不是“如何将我展现。”像其他的答案显示...
$c=count($a)>count($b)? $a:$b;
如果你想要一个功能
function largestArray($a, $b){
return count($a)>count($b)? $a:$b;
}
$c=largestArray($a, $b);
echo '$a size is '.count ($a).'<br>';
echo '$b size is '.count ($b).'<br>';
OR
if (count($a)==count($b))
echo '$a is same size as $b';
else
echo count($a)>count($b) ? '$a is bigger then $b' : '$b is bigger then $a';
你提到return
,所以我假设这一操作发生在一个函数:
<?php
// Create our comparison function
function compareArrays($array_1, $array_2) {
return count($array_1) > count($array_2) ? $array_1 : $array_2;
}
// Define the arrays we wish to compare
$a = array(2,3,4);
$b = array(1,2,3,4,5,6,7);
// Call our function, returning the larger array.
$larger_array = compareArrays($a, $b);
// Print the array, so we can see if logic is correct.
print_r($larger_array); // Prints: array(1,2,3,4,5,6,7)
要由史蒂芬留下评论扩展,你可以使用count
函数来确定数组的长度。然后使用三元运算符来选择哪一个更大。
<?php
$b= array(1,2,3,4,5,6,7);
$a = array(2,3,4);
var_dump((count($a) > count($b)) ? $a : $b);
count(array1) - count(array2)? – Steven 2013-03-20 19:16:40
你也可以做array_diff($ array1,$ array2)然后计算它。这也可以说阵列2缺少1,5,6,7。 – Steven 2013-03-20 19:20:10
我倾向于说,答案显然是你应该搜索一下旁边的阅读PHP手册:http://php.net/arrays; http://php.net/count – hakre 2013-06-23 12:14:49