PHP Array Length Function to Get Length of Arrays

PHP Arrays are collections of items identified and ordered by index.

Array length is just the number of elements it contains. For an array:

$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().

$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.

1 thought on “PHP Array Length Function to Get Length of Arrays”

  1. 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) …

Comments are closed.

Scroll to Top