An array is a group of data structures. In PHP, an array is mainly a list of things in order.
It might be helpful to be able to find out how many elements are in an array or if an array has more than one element.
In this how-to, we will learn how to check if an array has more than one element.
Solution #1
There is more than one way to solve this problem. The PHP count method is one way to do this.
The count methods take an array as an argument and tell you how many elements are in the array as a whole. We only need to check if this number is greater than one to know what to do.
if (count($your_array) > 1) {
//Do Something
}
Solution #2
The second thing we can do is use the PHP sizeof method. This method is just a name for the count method under a different name. So it still does the same job the same way.
if (sizeof($your_array) > 1) {
//Do Something
}
Solution #1 is the best way to find out if an array in PHP has more than one item. The count method will make your code look better because, in some languages, size means the amount of memory that has been allocated. This can make it harder to understand your code when you go back to it later.
To make your code a little more reliable, you might also want to make sure that your array is really an array and not something else. We can use the is array method to do this.
if (is_array($your_array) && count($your_array) > 1) {
//Do Something
}
But this check might only be needed in some situations.
So, you now know how to use PHP to check if an array has more than one item. This code is easy to change to see if an array has more than any number of elements. Happy Coding!