1

I want to output an address like this 123 Street, address, city, county, postcode

The data is stored in a database and i need to check to see if the field has anything in it so I know to output a comma in the address

$address = array($club['clubAdd1'], $club['clubAdd2'], $clubCity, $club['clubCounty'], $club['clubPostcode']);

3 Answers 3

3
$parts = array(

  $club['clubAdd1'],
  $club['clubAdd2'],
  $clubCity,
  $club['clubCounty'],
  $club['clubPostcode'],

);

$address = array();

foreach ($parts as $part)
{

  if ('' != $part)
  {
    $address[] = $part;
  }

}

echo implode(', ', $address);

Edit: one liner

  echo implode(', ', array_filter($array));

Edit 2: More accurate one liner

The problem with the above is that 0 and '0' will also be removed, which might not be desired behaviour. This will fix that:

array_filter($array, function ($value)
{
  return strlen(trim($value));
}
);
Sign up to request clarification or add additional context in comments.

4 Comments

This works great thanks, but why do i need two arrays? doesnt this just end up using more code?
Heh. Didn't actually look down. Just read his comment and responded. Sorry.
About "Edit 2", good point, but not likely given the OP is referring to address values.
True, but just in case the method is used in related non-address situations.
1

a one-liner

echo implode(', ', array_filter(array($club['clubAdd1'], $club['clubAdd2'], $clubCity, $club['clubCounty'], $club['clubPostcode'])))

Comments

1

Running the array through the array_filter() function, without a second argument, would return an array with no empty elements.

For example:

$address_line = implode(', ',array_filter($address_array));

As Michael have noted, this would also remove nnumeric 0 values.

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.