How to determine if an array has any elements or not? How to determine if an array has any elements or not? arrays arrays

How to determine if an array has any elements or not?


You can use the count() or sizeof() PHP functions:

if (sizeof($result) > 0) {    echo "array size is greater than zero";}else {    echo "array size is zero";}

Or you can use:

if (count($result) > 0) {    echo "array size is greater than zero";}else {    echo "array size is zero";}


count — Count all elements in an array, or something in an object

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Counts all elements in an array, or something in an object.

Example:

<?php    $a[0] = 1;    $a[1] = 3;    $a[2] = 5;    $result = count($a);    // $result == 3

In your case, it is like:

if (count($array) > 0){    // Execute some block of code here}


You could avoid length retrieve and check using a simple foreach:

foreach($result as $key=>$value) {    echo $value;}