Jump to content

'if exists' ?


simonp

Recommended Posts

Hi,

 

I want to display some variables but only if they exist (ie have something in them)

 

At the moment I have:

 

<textarea rows="6" name="bankaddress" style="width: 200px;"><?php echo $branch . ", " . $address1 . ", " . $address2 . ", " . $address3 . ", " . $address4 . ", " . $town . ", " . $county . ", " . $postcode; ?></textarea>

 

. . . which displays everything - but $address2, $address3 and $address4 are often empty. How can I say print $address2, a comma and a space unless $address2 is empty then ignore it?

 

Cheers

 

Simon

Link to comment
https://forums.phpfreaks.com/topic/64276-if-exists/
Share on other sites

ok - so now I'm using:

 

<textarea rows="6" name="bankaddress" style="width: 200px;"><?php if(isset($address1)){echo $address1 . ", ";} if(isset($address2)){echo $address2 . ", ";} if(isset($address3)){echo $address3 . ", ";} if(isset($address4)){echo $address4 . ", ";} if(isset($town)){echo $town . ", ";} if(isset($county)){echo $county . ", ";} if(isset($postcode)){echo $postcode . ", ";} ?></textarea>

 

Which produces:

 

Chapel Lane, , , , Formby, Merseyside, L37 4DN, 

 

So I'm guessing the values mustn't be empty - is there a way round this (I can't edit the values)?

Link to comment
https://forums.phpfreaks.com/topic/64276-if-exists/#findComment-320587
Share on other sites

Why can't you edit the values?

 

You could try:

if (strlen($address1) > 1 || ord($address1[0]) > 32)

 

The idea behind this is that, if $address1 has more than one character in it, it must be something of value. But just in case it has only one character that is of value, check if it is a good kind of character (not whitespaces and stuff.)

 

This could be a lot easier if you changed the values.

Link to comment
https://forums.phpfreaks.com/topic/64276-if-exists/#findComment-320597
Share on other sites

Instead of using the individual variables, I would use a temporary array:

 

<?php
$vars = array('branch','address1','address2','address','address4','town','county','postcode');
$tmp = array();
foreach ($vars as $v)
   if (isset($$v))
       $tmp[] = $$v;
echo '<textarea rows="6" name="bankaddress" style="width: 200px;">' . implode(', ',$tmp) . "</textarea>";
?>

 

Note: untested.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/64276-if-exists/#findComment-320655
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.