Which is a better way to check if an array has more than one element?
Solution 1:
Use this
if (sizeof($arr) > 1) {
....
}
Or
if (count($arr) > 1) {
....
}
sizeof()
is an alias for count()
, they work the same.
Edit:
Answering the second part of the question:
The two lines of codes in the question are not alternative methods, they perform different functions. The first checks if the value at $arr['1']
is set, while the second returns the number of elements in the array.
Solution 2:
if(is_array($arr) && count($arr) > 1)
Just to be sure that $arr is indeed an array.
sizeof
is an alias of count
, I prefer to use count because:
- 1 less character to type
- sizeof at a quick glance might mean a size of an array in terms of memory, too technical :(
Solution 3:
if (count($arr) >= 2)
{
// array has at least 2 elements
}
sizeof()
is an alias for count()
. Both work with non-arrays too, but they will only return values greater than 1 if the argument is either an array or a Countable
object, so you're pretty safe with this.
Solution 4:
Obviously using count($arr) > 1
(sizeof
is just an alias for count
) is the best solution.
Depending on the structure of your array, there might be tons of elements but no $array['1']
element.
Solution 5:
Use count()
if (count($my_array) > 1) {
// do
}
this page explains it pretty well http://phparraylength.com/