Php – Check if explode value count is greater than 0

PHP

I am retrieving some data from a table in mysql. The values are stored with a | separater
Example:
test 1|test 2|test 4 and so on..
Everything works great except when there are blank entries in the column. I am using the following code.

$groups = explode('|', $row['groups']);
if(count($groups) >0) 
{
   echo 'There are values';

}else{ 
   echo 'No values';
} 

The problem I have is this returns 'There are values' even if the column is empty.
Any help would be great appreciated.

Best Answer

explode

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned

<?php
$g = "";
$e = explode('|',$g, -1) ;
if ($e) print "yes 1"; else print "Non 1";

$g = "";
$e = explode('|',$g, 1) ;
if ($e) print "yes 2"; else print "Non 2";

?>

Non 1
yes 2

The issue is that your returned array contains a single element that is empty string.

Related Topic