PHP 中的集合對象的特點是有一個長度參數來指示其中包含的元素數量。為了執行數組操作和修改,有必要估計數組的長度。
sizeof()
sizeof() 方法用於計算數組或任何其他可數對象中存在的所有元素。它可用於uni-dimensional 以及多維數組。 sizeof()方法需要更長的執行時間。另外,sizeof() 方法是count() 方法的別名。
用法
sizeof(arr, mode);
參數
此方法接受下麵討論的兩個參數:
- arr -用於計算元素數量的數組。
- mode -檢查是否計算所有元素的指示器 -
- 0 - 默認。不計算多維數組的所有元素
- 1 - 遞歸地計算數組(計算多維數組的所有元素)。
例子:此示例說明了 PHP 中 sizeof() 方法的基本用法。
PHP
<?php
$arr = array(
"Java" => array(
"SpringBoot",
"Eclipse"
) ,
"Python" => array(
"Django"
) ,
"PHP" => array(
"CodeIgniter"
)
);
print_r($arr);
print ("<br>");
echo "Sub elements of an array: "
. sizeof($arr) . "<br>";
echo "All elements of an array: "
. sizeof($arr, 1);
?>
輸出:
Array (
[Java] => Array (
[0] => SpringBoot
[1] => Eclipse
)
[Python] => Array (
[0] => Django
)
[PHP] => Array (
[0] => CodeIgniter
)
)
Sub elements of an array: 3
All elements of an array: 7
count()
count() 方法用於計算數組或任何其他可數對象中的所有元素。它可用於uni-dimensional 以及多維數組。
用法
count(arr, mode);
參數
此方法接受下麵討論的兩個參數:
- arr -用於計算元素數量的數組。
- mode -檢查是否計算所有元素的指示器 -
- 0 - 默認。不計算多維數組的所有元素
- 1 - 遞歸地計算數組(計算多維數組的所有元素)。
示例:這個例子說明了PHP中count()方法的基本用法。
PHP
<?php
$arr = array(
"Java" => array(
"SpringBoot",
"Eclipse"
) ,
"Python" => array(
"Django"
) ,
"PHP" => array(
"CodeIgniter"
)
);
print_r($arr);
print ("<br>");
echo "Sub elements of an array: "
. count($arr) . "<br>";
echo "All elements of an array: "
. count($arr, 1);
?>
輸出
Array (
[Java] => Array (
[0] => SpringBoot
[1] => Eclipse
)
[Python] => Array (
[0] => Django
)
[PHP] => Array (
[0] => CodeIgniter
)
)
Sub elements of an array: 3
All elements of an array: 7
sizeof() 和 count() 方法之間的區別
sizeof()方法 |
count()方法 |
|
1. | sizeof() 函數用於返回數組中的元素數量。 | count() 返回數組中的元素數量。 |
2. |
它的語法是-: sizeof(數組,眾數) |
它的語法是-: 計數(數組,模式) |
3. | 它的返回值是整型。 | 它的返回值是整型。 |
4. | 該函數是count()函數的別名。 | 對於未設置的變量,count() 函數可能會返回 0。 |
5. | PHP 4.0+ 版本支持 | PHP 4.0+ 版本支持 |
綜上所述,PHP的count()和sizeof()方法沒有區別。一個方法是另一種方法的別名。由於sizeof()方法執行時間較長,因此count()方法被認為更好更快。
相關用法
- PHP count()用法及代碼示例
- PHP count_chars()用法及代碼示例
- PHP cos()用法及代碼示例
- PHP cosh()用法及代碼示例
- PHP copy()用法及代碼示例
- PHP collator_asort()用法及代碼示例
- PHP collator_compare()用法及代碼示例
- PHP collator_sort()用法及代碼示例
- PHP collator_sort_with_sort_keys()用法及代碼示例
- PHP compact()用法及代碼示例
- PHP connection_status()用法及代碼示例
- PHP convert_cyr_string()用法及代碼示例
- PHP convert_uuencode()用法及代碼示例
- PHP convert_uudecode()用法及代碼示例
- PHP constant()用法及代碼示例
- PHP ceil()用法及代碼示例
- PHP chgrp()用法及代碼示例
- PHP chmod()用法及代碼示例
- PHP chown()用法及代碼示例
- PHP clearstatcache()用法及代碼示例
- PHP call_to_jd()用法及代碼示例
- PHP crypt()用法及代碼示例
- PHP chroot()用法及代碼示例
- PHP closedir()用法及代碼示例
- PHP cal_days_in_month( )用法及代碼示例
注:本文由純淨天空篩選整理自yashchuahan大神的英文原創作品 What is the difference between count() and sizeof() functions in PHP ?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。