tags:

views:

58

answers:

3

I was wondering how would hide the text Location if the city state and country were not present and how would I let it display if any of the variables were present?

<p>Location:
<?php
 if (!empty($city))
     {
     echo $city .',';
     }

 if (!empty($state))
     {
     echo $state;
     }

 if (!empty($country))
     {
     echo ' ' . $country;
     }
?>    
</p>
+1  A: 

Wrap it in a PHP block as well:

<?php

// Check if any of them is not empty.
if(!empty($city) || !empty($state) || !empty($country)){
    echo "<p>Location:";
    if (!empty($city))
    {
        echo $city .',';
    }
    if (!empty($state))
    {
        echo $state;
    }
    if (!empty($country))
    {
        echo ' ' . $country;
    }
    echo "</p>";
}
Michael Stum
+2  A: 

Use:

<?php
 $address = "";
 if (!empty($city))
     {
     $address_parts[] = $city;
     }

 if (!empty($state))
     {
     $address_parts[] = $state;
     }

 if (!empty($country))
     {
     $address_parts[] = $country;
     }
$address = implode( ", ", $address_parts);
if (!empty($address)) 
{
 echo   "<p>Location: " . $address . "</p>";
}
?>

Build the address up and then test if the address is still empty before displaying location.

Edit
Changed how the address is built up. Rather than concatenate everything, the address parts are added to an array and then imploded with the appropriate separator.

Jonathan Fingland
A: 

in not exactly same but a similar problem, i used this method.

may be this helps you too:)

<?php
function publish($buffer){
global $location;
if (empty($location))
 $buffer="";
return $buffer;
}
ob_start("publish");

$location=$_GET["location"];
echo "Location: $location";

ob_end_flush();
?>

test the url with location parameter and without a parameter. And you can find more detail about this in php.net output control functions

H2O