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']);
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.
An array cannot be null.
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() 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 .
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 explode
ing weird strings):
foreach ($playerlist as $key => $value) { if (empty($value)) { unset($playerlist[$key]); } } if (empty($playerlist)) { //empty array }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With