Jump to content


Photo

How do I concatenate string with variable that is empty.

concat variables

Best Answer scosteve, 29 October 2013 - 01:13 PM

Thanks Rifts,

 

I used your method.  I knew that method was possible but I was hoping to avoid all the extra code.  I was looking for something that worked like the trim function in access.  This works though.

 

Thanks

Go to the full post


  • Please log in to reply
3 replies to this topic

#1 scosteve

scosteve

    Newbie

  • New Members
  • Pip
  • 2 posts

Posted 28 October 2013 - 05:03 PM

I need to echo a string of variables and depending on the input one may be empty.

 

I have for example,

 

$row['add_1'] = 15 north st

$row['add_2'] = Apt 2

$row['city'] = Macon

$row['state'] = GA

 

echo $row['add_1'] . ", " . $row['add_2'] . ", " . $row['city'] . ", " . $row['state']

 

this will output

15 north st, Apt 2, Macon, GA.

 

My problem occurs when $row['add_2'] is empty.

 

the output looks like this.

 

15 north st, , Macon, GA

 

How do I get rid of the extra comma if the variable is empty?

 

 

 

 



#2 Barand

Barand

    Sen . ( ile || sei )

  • Gurus
  • 13,885 posts
  • LocationCheshire, UK

Posted 28 October 2013 - 05:16 PM

Use array_filter() to remove empty items then join/implode

$row['add_1'] = '15 north st';
$row['add_2'] = '';
$row['city'] = 'Macon';
$row['state'] = 'GA';

echo join(', ', array_filter($row));  // --> 15 north st, Macon, GA

edit:

If the address elements are part of a larger array you can use array_slice() to extract them EG

$row['name'] = 'Fred';
$row['add_1'] = '15 north st';
$row['add_2'] = '';
$row['city'] = 'Macon';
$row['state'] = 'GA';
$row['phone'] = '132 456 7890';

echo join(', ', array_filter(array_slice($row,1,4)));  // --> 15 north st, Macon, GA


Edited by Barand, 28 October 2013 - 05:33 PM.

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts
|baaSelect| generate js and php code for dynamic linked dropdowns

 


#3 Rifts

Rifts

    Warlock

  • Members
  • PipPipPip
  • 702 posts
  • LocationAZ
  • Age:27

Posted 29 October 2013 - 12:51 PM

you could just check if that variable add_2 is empty then change your code.

if(empty( $row['add_2'])) {
 //dont include it
}

also issset() might work too

 

if you want to read more about empty, isset

http://techtalk.vire...pty-vs-is_null/


Edited by Rifts, 29 October 2013 - 12:52 PM.


#4 scosteve

scosteve

    Newbie

  • New Members
  • Pip
  • 2 posts

Posted 29 October 2013 - 01:13 PM   Best Answer

Thanks Rifts,

 

I used your method.  I knew that method was possible but I was hoping to avoid all the extra code.  I was looking for something that worked like the trim function in access.  This works though.

 

Thanks






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com