PHP Arrays are collections of items identified and ordered by index.
Array length is just the number of elements it contains. For an array:
<?php
$greetings = array(
'Good morning!',
'Good afternoon!',
'Good evening!'
);
?>
The length of array in PHP code above is simply the number of strings contained in it, in this case, that is 3. However, to get the php array length that’s created or modified on the fly, you need function count().
<?php
$length = count($greetings); // $length now equals to 3, which is the length of the php array.
?>
However, for a compound array which contains arrays as elements, the size of the array calculated by php array size function count() would only be taking the first level of elements into account.
You should also read:
- PHP: Divide and Split an Array into Chunks (Sections) or Several Sub-arrays
- jQuery: How to test or check whether an element exists
- PHP: Count the Number of Occurrences of Each Unique Value in an Array
- PHP String Length function to Get Length of Strings in PHP
- PHP: Count Lines of a File and Get the Number of Lines in a Text File


Facebook
Twitter
Google Plus
{ 1 comment… read it below or add one }
One addition. Some functions can return 0 or false instead of array if something wrong or resulting dataset is empty. In this case $greeting can be a simple variable, not an array and count($greetings) will return 1.
It can put some mess in the code. So I additionaly use is_array() function to be fully sure that I have an array with at least on element:
if (is_array($greetings) && count($greetings)>0) …