How to check if array is empty or not in PHP?

by verlie.homenick , in category: PHP , 2 years ago

How to check if array is empty or not in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@verlie.homenick You can use empty() function in PHP to check if array is empty or not, here is code as example:


1
2
3
4
5
6
7
8
<?php

$arr = [];

if (empty($arr)) {
    echo "Array is empty";
}
// Output: Array is empty
by laury_ullrich , a year ago

@verlie.homenick 

In PHP, you can use the empty() function to check if an array is empty or not.

1
2
3
4
5
if (empty($array)) {
    // array is empty
} else {
    // array is not empty
}


You can also use the count() function to check the number of elements in an array:

1
2
3
4
5
if (count($array) === 0) {
    // array is empty
} else {
    // array is not empty
}


Alternatively you can also use the !$array to check if array is empty.

1
2
3
4
5
if (!$array) {
    // array is empty
} else {
    // array is not empty
}


Note: empty() will return TRUE if the array has no elements, or if all of its elements are FALSE, and count() function returns the number of elements in an array.