2017-02-14 132 views
2

1)如何查找數組的大小
2)如何執行數組大小大於零的代碼塊?如何查找數組的大小

if($result > 0){ 
     /////////here is some code body which i want to execture///////// 
}eles{ 
    ///////some other code//////// 
} 
+7

count()函數if(count($ result)> 0) – bxN5

回答

5

你可以使用count()或的sizeof()PHP函數一樣

if(sizeof($result) > 0){ 
    echo "array size is greater then zero"; 
}else{ 
    echo "array size is zero"; 
} 

,或者你可以使用

if(count($result) > 0){ 
echo "array size is greater then zero"; 
}else{ 
    echo "array size is zero"; 
} 

我希望它會幫助你

7

count - 計數在一個陣列,或東西的所有元素中的對象

int count (mixed $array_or_countable [, int $mode = COUNT_NORMAL ]) 

計數陣列中的所有元件,或者在對象的東西。

例:

<?php 
$a[0] = 1; 
$a[1] = 3; 
$a[2] = 5; 
$result = count($a); 
// $result == 3 

在你的情況下,它是這樣的:

if (count($array) > 0) 
{ 
    // execute some block of code here 
} 
+0

如果我們計數超過一次,那麼我們可以再次在if條件中對它進行計數嗎? –

+0

您可以根據您的需要計算多次,但有時並不是必需的。儘量不要做不必要的事情,那會污染你的代碼。 – Zeke

2

你可以避開長檢索和查詢使用簡單的foreach

foreach($result as $key=>$value) { 
    echo $value ; 
} 
1

@Sajid馬哈茂德在PHP中,我們有計數()來計算一個數組的長度, 當計數()返回0,則意味着該數組爲空

允許以一個例子的理解

<?php 
    $arr1 = array(1); // with one value which will give 1 count 
    $arr2 = array(); // with no value which will give 0 count 

    //now i want that the arrray which has greater than 0 count should print other wise not so 

    if(count($arr1)){ 
     print_r($arr1); 
    } 
    else{ 
     echo "sorry array1 has 0 count"; 
    } 

    if(count($arr2)){ 
     print_r($arr2); 
    } 
    else{ 
     echo "sorry array2 has 0 count"; 
    }