Home  >  Article  >  Backend Development  >  How to get how many elements there are in an array in php

How to get how many elements there are in an array in php

青灯夜游
青灯夜游Original
2021-11-26 18:32:236114browse

php method to get how many elements there are in an array: 1. Use the count() function to count the number of all elements in the array, the syntax is "count(array,mode)"; 2. Use sizeof( ) function, which can calculate the number of elements in an array, the syntax is "sizeof(array,mode)".

How to get how many elements there are in an array in php

The operating environment of this tutorial: windows7 system, PHP version 7.1, DELL G3 computer

I want to count the number of array elements in PHP In fact, it is very simple. PHP provides us with two functions, namely count() and sizeof() functions.

In fact, the sizeof() function is an alias of the count() function, that is, the function and usage of the sizeof() function are exactly the same as the count() function.

Let’s introduce the count() function to you to understand these two functions.

The count() function can count the number of all elements in the array, or the number of attributes in the object. Its syntax format is as follows:

count(array,mode)

The parameter description is as follows:

  • array: is the array or object to be counted;
  • mode: is an optional parameter and can be omitted.
    • If the mode parameter is omitted or set to COUNT_NORMAL or 0, the count() function will not detect multi-dimensional arrays;
    • If the mode is set to COUNT_RECURSIVE or 1, the count() function will be recursive Calculate the number of elements in an array, especially useful for calculating the number of elements in multi-dimensional arrays.

Example 1: Count the number of elements in a one-dimensional array

<?php
header("Content-type:text/html;charset=utf-8");
$arr= array("香蕉","苹果","梨子","橙子","橘子","榴莲");
//输出语句
var_dump($arr);
echo "数组长度为:".count($arr);
?>

How to get how many elements there are in an array in php

Example 2: Count the number of elements in a two-dimensional array

<?php
header("Content-type:text/html;charset=utf-8");
$arr= array(
"张三",
25,
array("高数","PHP教程","英语")
);
//输出语句
var_dump($arr);
echo "数组长度为:".sizeof($arr,1);
?>

How to get how many elements there are in an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to get how many elements there are in an array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn