Backend Development 5 min read

How to Count the Number of Keys in a PHP Array

This article explains several PHP techniques—including the count function, array_keys, foreach loops, and end/key combination—to determine how many keys an array contains, providing code examples and explanations for each method.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Count the Number of Keys in a PHP Array

In PHP programming, arrays are a common data type, and determining how many keys an array contains can be done in several ways.

Method 1: count function

The built‑in count function returns the number of elements (keys) in an array. Pass the array as the argument.

<code>$myArray = array('apple', 'banana', 'cherry');
$count = count($myArray);
echo $count; // output: 3
</code>

This creates an array with three elements and uses count to store the length in $count , then prints 3.

Method 2: array_keys function

The array_keys function returns an array of all keys, which can then be counted with count .

<code>$myArray = array(
    'fruit1' => 'apple',
    'fruit2' => 'banana',
    'fruit3' => 'cherry'
);
$keys = array_keys($myArray);
$count = count($keys);
echo $count; // output: 3
</code>

Here an associative array with three key‑value pairs is created, its keys are extracted, and the number of keys is counted.

Method 3: foreach loop

A manual counter can be incremented while iterating over the array with foreach .

<code>$myArray = array(
    'fruit1' => 'apple',
    'fruit2' => 'banana',
    'fruit3' => 'cherry'
);
$count = 0;
foreach ($myArray as $key => $value) {
    $count++;
}
echo $count; // output: 3
</code>

The loop visits each element, increments $count , and finally outputs the total.

Method 4: end and key functions

By moving the internal pointer to the last element with end and retrieving its key with key , adding one yields the array length (assuming consecutive numeric keys).

<code>$myArray = array(
    'fruit1' => 'apple',
    'fruit2' => 'banana',
    'fruit3' => 'cherry'
);
end($myArray);
$count = key($myArray) + 1;
echo $count; // output: 3
</code>

This approach also results in the count of keys.

Conclusion

PHP offers multiple ways to count array keys, including count , array_keys , a foreach loop, and the combination of end and key . Knowing these methods helps understand PHP arrays and avoid common mistakes.

backendProgrammingArraycount()
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.