问题
How can I 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 am after null
or just something like $empty_array = '';
whenever they are found empty.
回答1:
What about this:
function convert($array) {
return (count($array) === 0) ? "" : $array;
}
$empty_array = array();
$empty_array = convert($empty_array);
This will simply convert it into a empty string if the array is empty.
An object is somewhat 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 on private variables.
回答2:
Using implode()
for the simpler solution.
echo implode('',(array)$array_or_object);
来源:https://stackoverflow.com/questions/10471387/how-to-convert-an-empty-array-and-empty-object-to-an-empty-string-or-null