[php] Which is a better way to check if an array has more than one element?

I just need to check if an array has more than one element. I am trying to do it this way :

if (isset($arr['1']))

the other traditional way is

if (sizeof($arr)>1)

Which of the two is better? In such situaions, how should I judge between two alternate methods? Is there any performance check meter available to measure which is better?

This question is related to php arrays

The answer is


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.


I do my array looping and getting filled defaults accordingly in Swift 4/5

   for index in 0..<3
    {
        let isIndexValid = allObjects.indices.contains(index)
        var yourObject:Class = Class()
        if isIndexValid { yourObject = allObjects[index]}
        resultArray.append(yourObject)
    }

For checking an array empty() is better than sizeof().

If the array contains huge amount of data. It will takes more times for counting the size of the array. But checking empty is always easy.

//for empty
  if(!empty($array))
     echo 'Data exist';
  else 
     echo 'No data';


 //for sizeof
 if(sizeof($array)>1)
      echo 'Data exist';
 else 
    echo 'No data';

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. 1 less character to type
  2. sizeof at a quick glance might mean a size of an array in terms of memory, too technical :(

The first method if (isset($arr['1'])) will not work on an associative array.

For example, the following code displays "Nope, not more than one."

$arr = array(
    'a' => 'apple',
    'b' => 'banana',
);

if (isset($arr['1'])) {
    echo "Yup, more than one.";
} else {
    echo "Nope, not more than one.";
}

isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains


I assume $arr is an array then this is what you are looking for

if ( sizeof($arr) > 1) ...

I prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages. Many programmers expect sizeof() to return the amount of memory allocated.


Use count()

if (count($my_array) > 1) {
// do
}

this page explains it pretty well http://phparraylength.com/


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.