Home  >  Article  >  Backend Development  >  How to get the length of an array in php

How to get the length of an array in php

PHPz
PHPzOriginal
2023-04-17 14:58:25551browse

In PHP, we usually use the count() function to get the length of an array, also known as the number of array elements or the size of the array.

The count() function can be used with any type of array, including indexed arrays and associative arrays. It can even be used to handle arrays with mixed keys and values.

Here are a few examples of using the count() function to get the array length:

  1. Get the index array length
$numbers = array(1, 2, 3, 4, 5);
$size = count($numbers);
echo "数组长度是:" . $size;

The above code will output the following Result:

数组长度是:5
  1. Get the associative array length
$fruits = array(
    "apple" => 2,
    "banana" => 4,
    "orange" => 6
);
$size = count($fruits);
echo "数组长度是:" . $size;

The above code will output the following results:

数组长度是:3
  1. Get the mixed array length
$mix = array(
    "apple" => 2,
    1,
    "orange" => 6,
    3
);
$size = count($mix);
echo "数组长度是:" . $size;

The above code will output the following results:

数组长度是:4

In some cases, it may be necessary or desirable to manually calculate the length of the array instead of using the count() function, such as for associations Array or array with custom keys.

The following is an example of manually calculating the length of an array:

  1. For indexed arrays, you can use the count() function and loop:
$numbers = array(1, 2, 3, 4, 5);
$size = 0;
foreach ($numbers as $value) {
    $size++;
}
echo "数组长度是:" . $size;
  1. For associative arrays, you can use a foreach loop:
$fruits = array(
    "apple" => 2,
    "banana" => 4,
    "orange" => 6
);
$size = 0;
foreach ($fruits as $key => $value) {
    $size++;
}
echo "数组长度是:" . $size;

The method of manually counting the number of elements in the array may be more suitable for processing specific types of arrays or data structures, depending on your application.

The above is the detailed content of How to get the length of 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