1

Rookie question but can someone help with a simple function to skip empty variables during concatenation in PHP and add a comma.

Example;

$addressline1 = "Street";
$addressline2 = "";
$addressline3 = "London";

I want to get;

$concataddress = "Street, London";

And not;

$concataddress = "Street, , London";

I'm getting the addresses from mysql DB I can obviously use if...else statement and check if(empty($addressline1)) etc but looking for something efficient and simple.

Thanks!

5
  • What is your code to concat for now ? Commented Nov 11, 2015 at 9:33
  • $concataddress = str_replace(" ,", "", $contactaddress); Commented Nov 11, 2015 at 9:34
  • 2
    implode(', ',array_filter(array($addressline1,$addressline2...))) Commented Nov 11, 2015 at 9:35
  • Why are you thinking if(){}else{} and inbuild functions e.g. empty() are not efficient and simple? Commented Nov 11, 2015 at 9:38
  • @Vatev thanks mate. Please put it as answer and I'll accept. Commented Nov 11, 2015 at 9:46

4 Answers 4

2

You could place them in an array and use array filter with implode

$address = implode(", ", array_filter(array($addressline1, $addressline2, $addressline3));
Sign up to request clarification or add additional context in comments.

2 Comments

Boom. Beat me to it :)
Looks like @Vatev beat me to it too
1

array_filter without a callback will remove all elements which evaluate to false.

$concatAddress = implode(', ', array_filter(array(
    $addressline1,
    $addressline2,
    $addressline3,
    ...
)));

Comments

0

Try what Vatev suggested:

$array = array(
    'Street',
    '',
    'London',
);

$concatAddress = implode(', ', array_filter($array));

echo $concatAddress;

Comments

-1

You won't get much more efficient with variablenames.

If you store it in an array, you might get more efficient, in the way your code looks good, not in speed really.

for example:

function getAdres($ARR_adresParts){
  $adres = array();
  foreach($ARR_adresParts as $onePart){
    if ($onePart !== ""){
      $adres[] = $onePart;
    }
  }
  return implode(", ",$adres);
}

And then call it like:

$adr = getAdres(array($addressline1,$addressline2,$addressline3));

Not nice, but given the situation I doubt it will become more beautiful then something like that. :-)

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.