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

一世执手 提交于 2019-12-25 02:34:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!