函式名稱:count() 適用版本:PHP 4, PHP 5, PHP 7
函式描述:count() 函式用於獲取陣列中元素的個數或物件中屬性的個數。
用法示例:
- 獲取陣列元素的個數:
$fruits = array("apple", "banana", "cherry");
$fruitCount = count($fruits);
echo "陣列的元素個數為:" . $fruitCount; // 輸出: 陣列的元素個數為:3
- 獲取物件屬性的個數:
class Person {
public $name;
public $age;
}
$person = new Person();
$person->name = "John";
$person->age = 30;
$propertyCount = count((array)$person);
echo "物件屬性個數為:" . $propertyCount; // 輸出: 物件屬性個數為:2
注意事項:
- 如果傳遞的引數不是陣列或物件,則會返回 1。
- 如果傳遞的引數是 NULL,則會返回 0。
- 如果傳遞的引數是一個多維陣列,count() 函式只會計算第一層的元素個數。
- 物件屬性的計數是透過將物件轉換為陣列後進行計算。可以使用強制型別轉換
(array)
將物件轉換為陣列。 - 對於具有大量元素的陣列或物件,請謹慎使用 count() 函式,因為它的執行會消耗一定的效能。