An in-depth understanding of the PHP array count function _php instance

Source: Internet
Author: User

Count ()

The PHP count () function calculates the number of cells in an array or the number of attributes in an object, returns the number of cells in an array, or the number of properties in an object.

Grammar:

int count (mixed var [, int mode]) if Var is a normal variable of an array, returns 1 and returns 0 for nonexistent, uninitialized, or empty arrays.

The optional parameter mode is set to Count_recursive (or 1) and count () is recursively counted, which is especially useful for all cells that compute multidimensional arrays, but count () does not recognize infinite recursion. The default value for mode is 0.

Example:

<?php
Echo Count ($x);      Output: 0
$a = 2;
echo count ($a);      Output: 1
$arr _age = Array (a);
echo Count ($arr _age);    Output: 3
?>

sizeof () is an alias for this function.

In practice, some loops are often performed based on the size of the array, and it is recommended that count () be written outside of the loop body:

<?php
$arr _age = Array (a);
$count = count ($arr _age);
For ($i =1 $i <= $count; $i + +) {
  echo "$i secondary loop";
}
? >

This does not have to perform the count () calculation every loop, of course this is not necessary.

The above in-depth understanding of the PHP array of the Count function is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.