PHP Array Size

PHP array size is important when we will be manipulating the contents of our array. By virtue of us using an array to store our variables in the first place, it usually means that we plan to operate on them as a unit.

Since we usually use for loops to process arrays, we need to know the array size so that we can know when to end the loop.

The following tutorial on the PHP array size explains.

Get PHP array size

There are two functions which can be used to get the size of an array. There is the count function and another function which is the alias of the aforementioned function called sizeof.

Any of these functions can be used interchangeably but since sizeof is an alias, we will stick to using the count function.

PHP Array size Example

Suppose we had the following code.

<?php
 
$temp = array('apple', 'banana', 'orange', 'mango');
 
echo count($temp);
echo '<br />';
echo sizeof($temp);
 
?>

The result would be:

4
4

As we expect, the result of both functions is 4 since there are 4 elements in the array and the functions do the same thing; return the array size.

So, now that we have a way of knowing how many elements are in the array we can go ahead and use a PHP for loop to process the array like so:

<?php
 
$temp = array('apple', 'banana', 'orange', 'mango');
 
for ($i = 0; $i < count($temp); $i++)
    echo $temp[$i] . '<br />';
 
?>

The result would be:

apple
banana
orange
mango

So as we can see, if we did not know the size of the array, we would have a more difficult time when trying to extract all the elements from it. The PHP array size function, count, helps us in that it allows us to know when to terminate the loop that we are using to process the array.

As you should also remember, the first element in the array is element 0. Therefore our loop must start counting at 0 and not 1. If we started counting at 1, we would miss the first element in our array. In the above example, we would miss the element 'apple'.

PHP Multidimensional Array Size

The way we use the count function above will not work to count all the elements in a multidimensional array. The perform this type of count, we need to pass an additional parameter to the function.

Look at this example:

<?php
 
$people = array('male' => array('Vince', 'Kevin', 'Jason'),
              'female' => array('Suzanne', 'Jodi', 'Jessica'));
 
echo count($people); // simple count
echo '<br />';
echo count($people, COUNT_RECURSIVE); // recursive count
 
?>

The result is:

2
8

When we did the simple count, PHP found that the array contained 2 variables. It did not care that these 2 variables were also arrays.

For the recursive count, we instruct PHP to look deeper and count the elements in nested arrays as well. This is when the get the other 6 variables for a total array element count of 8.

As always, we hope you found this PHP tutorial useful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...