2013-03-20 38 views
0

如何比較PHP中的兩個數組並找出哪兩個數組中的元素比另一個多?我怎樣才能找出2個數組中有哪些元素更多?

例如,我有數組

$a = array(2,3,4); 
$b = array(1,2,3,4,5,6,7); 

我將如何能夠動態地返回the array $b因爲它有更多的元素?有沒有PHP中的內置函數呢?

+1

count(array1) - count(array2)? – Steven 2013-03-20 19:16:40

+0

你也可以做array_diff($ array1,$ array2)然後計算它。這也可以說陣列2缺少1,5,6,7。 – Steven 2013-03-20 19:20:10

+0

我傾向於說,答案顯然是你應該搜索一下旁邊的閱讀PHP手冊:http://php.net/arrays; http://php.net/count – hakre 2013-06-23 12:14:49

回答

4

要回答這個問題「我怎麼會是能夠動態地返回......」不是「如何將我展現。」像其他的答案顯示...

$c=count($a)>count($b)? $a:$b; 

如果你想要一個功能

function largestArray($a, $b){ 
    return count($a)>count($b)? $a:$b; 
} 

$c=largestArray($a, $b); 
+0

謝謝!它實際上很簡單.. – Rogers 2013-03-20 20:17:08

+2

你在那裏寫的'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' – NikiC 2013-06-23 12:26:10

0
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'; 
1

你提到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) 
1

要由史蒂芬留下評論擴展,你可以使用count函數來確定數組的長度。然後使用三元運算符來選擇哪一個更大。

<?php 

$b= array(1,2,3,4,5,6,7); 
$a = array(2,3,4); 

var_dump((count($a) > count($b)) ? $a : $b); 
相關問題