0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the answer. what about an empty object? sorry please see my edit above.
0

Using implode() for the simpler solution.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.