Home >Backend Development >PHP Problem >What is an empty array in php
In PHP, an array with a length of 0 is called an empty array; an empty array is a real object, but it contains 0 elements. PHP has two functions to get the length of an array: count() and sizeof(), the syntax is "count($arr,$m)" or "sizeof($arr,$m)", and its parameter "$m" is used to handle multi-dimensional Array, can be omitted, if the value is set to 1, the length of the multi-dimensional array can be calculated; they can be used to detect whether an array is an empty array, the syntax is "array length == 0", if equal, it is an empty array.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
The empty space in php Array
An array with a length of 0 is called an "empty array". An empty array is a real object that only contains 0 elements.
<?php $arr1=array(); $arr2=[]; var_dump($arr1); var_dump($arr2); ?>
It can be seen that the arrays $arr1 and $arr2 do not contain elements, their length is 0, and they are empty arrays.
Note: In PHP, two functions are provided to calculate the length of the array, namely count() and sizeof() functions.
We can use these two functions to determine whether an array is an empty array.
1. Use the count() function to determine whether it is an empty array.
count($arr,$m)
The function is used to count all elements in the array. If the number of elements in the array is zero, then it will display an empty array.
$m: is an optional parameter and can be omitted.
If the $m parameter is omitted, or set to COUNT_NORMAL or 0, the count() function will not detect multidimensional arrays;
If If $m is set to COUNT_RECURSIVE or 1, the count() function will recursively calculate the number of elements in the array, which is especially useful for calculating the number of elements in multi-dimensional arrays.
<?php header("content-type:text/html;charset=utf-8"); // 声明一个空数组 $empty_array = array(); // 检查数组是否为空 if(count($empty_array) == 0) echo "数组为空"; else echo "数组不为空"; ?>
Output:
2. Use the sizeof() function to determine whether it is an empty array.
sizeof($arr,$m)
The function is an alias of the count() function, that is, the function and usage of the sizeof() function are completely the same as the count() function. same.
<?php header("content-type:text/html;charset=utf-8"); // 声明一个空数组 $empty_array = array(); if( sizeof($empty_array) == 0 ) echo "数组为空"; else echo "数组不空"; ?>
Output:
数组为空
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What is an empty array in php. For more information, please follow other related articles on the PHP Chinese website!