Skip to content

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

There are several ways to check if an array has more than one element in PHP. Here are a few options:

  1. Using the count function:

Example of using the count() function to check if an array has more than one element in PHP

php
<?php

$array = [1, 2, 3];

if (count($array) > 1) {
  echo "The array has more than one element.";
}
  1. Using the sizeof function:

Example of using the sizeof() function to check if an array has more than one element in PHP

php
<?php

$array = [1, 2, 3];

if (sizeof($array) > 1) {
  echo "The array has more than one element.";
}

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

  1. Using the count method of the ArrayObject class:

Example of using the count() method of ArrayObject class to check if an array has more than one element in PHP

php
<?php

$array = [1, 2, 3];
$arrayObject = new ArrayObject($array);

if ($arrayObject->count() > 1) {
  echo "The array has more than one element.";
}
  1. Using the ternary operator:

Example of using the ternary operator to check if an array has more than one element in PHP

php
<?php

$array = [1, 2, 3];
$result = count($array) > 1 ? 'more than one element' : 'one element or less';

echo $result;

All of these options will work to check if an array has more than one element. The best option for you will depend on your specific needs and personal preference.

Dual-run preview — compare with live Symfony routes.