Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print NULL fields from array using implode PHP?

Tags:

php

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!

like image 623
Cristiam Mercado Avatar asked Sep 26 '26 04:09

Cristiam Mercado


1 Answers

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);
like image 127
keune Avatar answered Sep 28 '26 19:09

keune