3

I have a strange problem. I have this piece of code:

$array = array('abc',null,'def',null);
$implode = implode(",", $array);
var_dump($implode);

and the result is:

string 'abc,,def,' (length=9)

Is there any way I can print null as a string? I mean, some thing like this:

string 'abc,null,def,null' (length=17)

Thanks a lot!

EDIT:

Thank you all for your responses. I think they are the same, but developed differently. I was thinking in array_map but I didn't know exactly how to use it. Thanks!

2 Answers 2

6

You could use array_walk to go over every item in the array and turn them to string if they are null:

$array = array('abc',null,'def',null);
function x(&$el) {
    $el = ($el === null) ? 'null' : $el;
}
array_walk($array, 'x');
$implode = implode(",", $array);
var_dump($implode);
Sign up to request clarification or add additional context in comments.

1 Comment

I was just about to post the same solution. Too fast 4 me ;)
1

You could map the nulls before.

$arrayMapped = array_map(function ($val) { return $val != null ? $val : 'null';}, $array);

$implode = implode(",", $arrayMapped);

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.