By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Determine PHP Array Length

How you can get the length of an array in PHP, and loop trough the results.

Edited: 2014-12-28 04:23

It can often be useful to know the length of an array, sometimes you need to know the length of an array when you want to loop trough the array. You can easily find the length of an array – or count the elements in the array – using the PHP count function.

You should note that counting the array elements, ain't really necessary, unless you don't know how many elements is in the array. Often when performing database queries, you won't know how many results are returned.

Below example shows how to count an array that we first create – of course it wouldn't necessary to count an array that we already know the length of – this is purely for educational purposes.

<?php
$aCoolStuff['php'] = "PHP is Cool";
$aCoolStuff['css'] = "CSS is Cool";
$aCoolStuff['html'] = "HTML is Cool";

echo count($aCoolStuff); // 3
?>

How to determine the length of an array

The below example shows how to count the elements in an array, which contains the results from the str_word_count function – the str_word_count function is used to count the number of words in a string – example follows:

<?php
 $str = "How to count the words in a string, and return the count afterwards.";
 $aWords = str_word_count($str, 1);

 $n = count($aWords); // Number of Pieces

 $counter = 0;
 while ($counter < $n) {
   echo $aWords["$counter"] . '<br>';
   ++$counter;
 }
?>

See also: Count the number of words with PHP

Counting multidimensional arrays

As you may already know, it is also possible to hold arrays inside of other array elements, to get the php array length of multidimensional arrays, you may want to use the second parameter of the count function.

The second parameter of count is called mode, and it is used to count recursively. The below example shows to use this in practice:

<?php
$aMyPHPArray['0'] = "Key1 content";
$aMyPHPArray['1'] = array(
  'SubKey1' => 'SubKey1 content',
  'SubKey2' => 'SubKey2 content');
$aMyPHPArray['2'] = "Key2 content";

 $n = count($aMyPHPArray, 1); // Number of elements in array

echo $n; // returns 5
?>

More Array Tutorials

  1. Find Elements or Keys in Array
  2. How to Loop Through an Array
  3. Create an Array From a List of Keywords with Explode
  4. Get Array Key and Value in PHP Foreach