[Solved] getting implode to ignore a NULL value

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

[Solved] getting implode to ignore a NULL value

Post 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 ?
Last edited by andym01480 on Fri May 04, 2007 3:47 pm, edited 1 time in total.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: getting implode to ignore a NULL value

Post 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';
Last edited by Kieran Huggins on Fri May 04, 2007 3:46 pm, edited 1 time in total.
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Ta very much. I could and did and it worked!
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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);')));
Post Reply