What is PHP?
PHP is a server-side scripting language that is widely used for web development. PHP supports many protocols and standards, such as HTTP, SMTP, POP3, IMAP, FTP, and XML. PHP can seamlessly integrate with other web development technologies, such as HTML, CSS, JavaScript. One of the key benefits of PHP is its cross-platform compatibility, which means that it can run on multiple operating systems, including macOS, Windows, Linux, and Unix.
What is an array in PHP?
In PHP, an array is a data structure that enables us to store multiple values under a single variable. Each element in an array is associated with a unique index or key, which can be either a string or a number. PHP supports two types of arrays: indexed arrays and associative arrays. Additionally, PHP provides a wide range of built-in functions that can be used to manipulate arrays, including searching, sorting, splitting a string to array, getting the length of an array, converting an string, and converting an array into JSON.
How to count the length of the PHP array?
You can use the count() function to count the length of the specified array. The sizeof() function is an alias for the count() function. The count() function takes two arguments, a list and a length count mode for nested arrays.
Where:
- array: specifies an array to count
- mode (Optional): specifies the counting mode. Possible values:
0 - is the default. It doesn't count all elements of multidimensional arrays
1 - Counts an array recursively (counts all elements of multidimensional arrays)
PHP Getting Length Array Examples
The following are examples of getting the length of an array in PHP:
Getting the Length of an Array using count()
The following is an example of getting the length of an array in PHP using count():
Getting the length of an array using sizeof()
The following is an example of getting the length of an array in PHP using sizeof():
Getting the length of a nested array
The following is an example of getting the length of a PHP array using the count() function with the "COUNT_RECURSIVE" parameter. The parameter specifies to recursively count the number of elements in the array, including elements in nested arrays.
Getting the length of an array that satisfies a condition
The following is an example of getting the length of an array that satisfies a given condition using array_filter(). We then use the count() function to count the number of elements in the new array.