Page 1 of 1

[Solved] getting implode to ignore a NULL value

Posted: Fri May 04, 2007 3:37 pm
by andym01480
I want to output addresses from a database. Not everyone has a subdistrict for their address so that key's value could be NULL

Trouble is implode doesn't ignore NULL values
To illustrate...

Code: Select all

<?php
//simulated database mysql_fetch_assoc values
$addrow['add1']="street";
$addrow['add2']=NULL;
$addrow['town']="town";
$addrow['county']="county";
$addrow['postcode']="postcode";

$add=implode(", ",$addrow);
echo $add;
?>
Outputs

Code: Select all

street, , town, county, postcode
Is there something simple I can do to make it less daft looking ?

Re: getting implode to ignore a NULL value

Posted: Fri May 04, 2007 3:45 pm
by Kieran Huggins
could try filtering the NULL fields from the array:

Code: Select all

$add=implode(", ",array_filter($addrow));
keep in mind this will remove all keys whose values evaluate as false, including false, '' and possibly '0';

Posted: Fri May 04, 2007 3:46 pm
by andym01480
Ta very much. I could and did and it worked!

Posted: Fri May 04, 2007 3:49 pm
by Kieran Huggins
you could be more specific by creating a callback function to evaluate NULL (untested):

Code: Select all

$add=implode(", ",array_filter($addrow,create_function('$v','return !is_null($v);')));