Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an array is empty using PHP?

Tags:

arrays

php

players will either be empty or a comma separated list (or a single value). What is the easiest way to check if it's empty? I'm assuming I can do so as soon as I fetch the $gameresult array into $gamerow? In this case it would probably be more efficient to skip exploding the $playerlist if it's empty, but for the sake of argument, how would I check if an array is empty as well?

$gamerow = mysql_fetch_array($gameresult); $playerlist = explode(",", $gamerow['players']); 
like image 981
aslum Avatar asked Feb 07 '10 05:02

aslum


People also ask

How do you check if an array is empty?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.

Is array null in PHP?

An array cannot be null.

Is empty in PHP?

PHP empty() FunctionThe empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

Is null or empty PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .


1 Answers

If you just need to check if there are ANY elements in the array

if (empty($playerlist)) {      // list is empty. } 

If you need to clean out empty values before checking (generally done to prevent explodeing weird strings):

foreach ($playerlist as $key => $value) {     if (empty($value)) {        unset($playerlist[$key]);     } } if (empty($playerlist)) {    //empty array } 
like image 153
Tyler Carter Avatar answered Oct 06 '22 23:10

Tyler Carter