How to convert an empty array and an empty object to an empty string or null

How to convert an empty array to an empty string or null ?

 $empty_array = array(); var_dump($empty_array); 

result

 array(0) { } 

Also for an empty object below

 class null_object{}; $null_object = new null_object(); var_dump($null_object); 

result

 object(null_object)#4 (0) { } 

I'm after null or just something like $empty_array = ''; whenever they are considered empty.

0
source share
2 answers

How about this:

 function convert($array) { return (count($array) === 0) ? "" : $array; } $empty_array = array(); $empty_array = convert($empty_array); 

This just converts it to an empty string if the array is empty.

The object is a bit more complicated, but you can just use get_object_vars () :

 function convert($object) { return (count(get_object_vars($object)) === 0) ? "" : $object; } 

Nb .: You cannot check an object for private variables.

+1
source

Using implode() for a simpler solution.

 echo implode('',(array)$array_or_object); 
0
source

All Articles