Here is my current address string: $address=$address1.", ".$address2.", ".$district.", ".$town.", ".$county.", ".$postcode; Code (markup): The problem is sometimes a client does not provide an 'address2' or 'district', in some cases both are not provided in which case the address string has unnecessary comma's in. How can I get around this problem?
Try something simple like: $address2 = !empty($address2) ? $address2.", " : ""; $district = !empty($district) ? $district.", " : ""; This will append a comma to the $address2/$district variable only if it is not empty. Then in your concat string you can try... $address=$address1.", ".$address2.$district.$town.", ".$county.", ".$postcode; Hope this helps
If all else fails, you may be able to read up on arrays here- http://www.jwrmedia.com/lessons/php/array
tonybogs - Seems like a good solution but I'm thinking there must be a more 'elegant' way of doing this? bigpapa - I've worked with arrays before but how would I use an array in this scenario?
//testing variables: $address1 = "1 Bd Zerktouni"; $town = "Casablanca"; $country = "Morocco"; //My suggestion f $address = ''; $address_parts = array('address1', 'address2', 'district', 'town', 'country', 'postcode'); foreach($address_parts as $address_part){ if(isset($$address_part) && trim($$address_part)) $address.= $$address_part.', '; } $address = substr($address, 0, -2); // removes the last ', ' echo $address; //Output: 1 Bd Zerktouni, Casablanca, Morocco PHP: