PHP Array Length Tutorial With Example

We will get php array length using len() and size() method. This tutorial help to find total number of elements into an array. The PHP provides many method to find php length of array.

You can count number of elements into an array using PHP functions count() and sizeof().

We will discuss these methods in this tutorial. The array can contain string and integer values. The array can be single dimensional or multidimensional.

Also checkout other related tutorials,

PHP Array Count with Example

The count(array, mode) method takes two parameters, One is required(array name) and second(for multi dimensional array count element) is optional.The count() will return 0 if the array is empty. And, if the variable specified is not an array, then, The count method will return 1.

Syntax:

count(var array, mode)

The first argument is an array variable that’s needed to calculate the PHP array length. The second argument is optional and it can take two values either COUNT_NORMAL or COUNT_RECURSIVE.

The count() function will emit an E_WARNING error if a variable isn’t an array or a Countable object.

PHP Get Array Length Using count() Method

We can use count method as like below –

$num = array(1, 2, 3, array(4, 5, 6));
echo count($num)."\n";
echo count($num, 1);

Output:

4 
7

PHP Get Array Size Using sizeof()

The sizeof() method is the alias of count function. This method function returns the number of elements in an array.

Syntax:
sizeof(array, mode);

The array is the required element and which contains all elements. The mode parameter is optional – 0, Does not count all elements of multidimensional arrays.1, Counts the array recursively (counts all the elements of multidimensional arrays).

PHP Check Array Length

We can use sizeof() method to get length of array in php, You can use sizeof method as like below –

$num = array(1, 2, 3, array(4, 5, 6));
echo sizeof($num)."\n";
echo sizeof($num, 1);

Output:

4 
7

Leave a Reply

Your email address will not be published. Required fields are marked *