Home >Backend Development >PHP Problem >PHP method to return the number of arrays

PHP method to return the number of arrays

王林
王林Original
2023-05-06 10:02:07569browse

In PHP, there are many ways to return the number of arrays. The following are four commonly used methods:

  1. count() function: This is one of the most commonly used functions among PHP's built-in functions. Use this function to return the number of elements in an array. It's very simple to use, just pass an array as a parameter and store the return value in a variable.

For example:

$array = array('apple', 'banana', 'cherry', 'date');
$count = count($array);
echo $count; //输出结果为4
  1. sizeof() function: This function has exactly the same function as count(). It also returns the number of elements in the array, just the function name is different. The usage method is the same as count().

For example:

$array = array('apple', 'banana', 'cherry', 'date');
$size = sizeof($array);
echo $size; //输出结果为4
  1. array_count_values() function: This function can count the number of occurrences of each element in the array and return a new array, where the key represents the element The value represents the number of times the element appears. Use this function to count the number of repeated elements very conveniently.

For example:

$array = array('apple', 'banana', 'cherry', 'banana', 'apple', 'date');
$count_array = array_count_values($array);
print_r($count_array);
//输出结果为:
//Array
//(
//    [apple] => 2
//    [banana] => 2
//    [cherry] => 1
//    [date] => 1
//)
  1. The difference between sizeof() and count() methods: Although these two functions have the same effect, in some special cases, their Behavior may vary. Usually, they are equivalent.

However, when the array is an object, the count() function calls the object's __count() method to count the number of elements. If the object does not define this method, an error will be thrown.

The sizeof() function does not call this method, it just returns the number of attributes in the object.

For example:

class MyArray implements Countable {
    private $array;

    public function __construct() {
        $this->array = array('apple', 'banana', 'cherry', 'date');
    }

    public function count() {
        return count($this->array) + 1;
    }
}

$my_array = new MyArray();

echo count($my_array); //输出结果为5

echo sizeof($my_array); //输出结果为1

The above is the detailed content of PHP method to return the number of arrays. 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