如何正確使用php sizeof函數(shù)

PHP
小樊
83
2024-07-13 21:13:21
欄目: 編程語言

在PHP中,sizeof() 函數(shù)用于返回?cái)?shù)組或?qū)ο蟮拈L度或元素個(gè)數(shù)。以下是一些正確使用 sizeof() 函數(shù)的示例:

  1. 返回?cái)?shù)組的元素個(gè)數(shù):
$array = array(1, 2, 3, 4, 5);
$length = sizeof($array);
echo $length; // Output: 5
  1. 返回關(guān)聯(lián)數(shù)組的元素個(gè)數(shù):
$assoc_array = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$length = sizeof($assoc_array);
echo $length; // Output: 3
  1. 返回對(duì)象的屬性個(gè)數(shù):
class Person {
    public $name = 'John';
    public $age = 30;
    public $city = 'New York';
}

$person = new Person();
$length = sizeof((array) $person);
echo $length; // Output: 3

請(qǐng)注意,sizeof() 函數(shù)是 count() 函數(shù)的別名,因此也可以使用 count() 來獲得數(shù)組或?qū)ο蟮拈L度。

0