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
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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.