I have three (optionally entered) post variables: city, state, and country. I'm unsure how to check to see which three are not empty and then insert commas between them accordingly. Someone might only enter a city, enter a city and state, only a city and country, etc. I know t开发者_开发百科here's an easy way of doing this but I'm having trouble doing it without making it many more lines of code than I need. Example:
<?php
$country = $_POST['country'];
$state = $_POST['state'];
$city = $_POST['city'];
if (!empty($city)){
$location = $city;
}
if (!empty($state) && !empty($city)){
$location .= ', ' . $state;
}
if (!empty($ state) ** !empty$country)){
$location .= ', '. $country;
}
echo $location;
?>
$location = array();
if(!empty($_POST['country'])) $location['country'] = $_POST['country'];
if(!empty($_POST['state'])) $location['state'] = $_POST['state'];
if(!empty($_POST['city'])) $location['city'] = $_POST['city'];
$location = implode(', ', $location);
Security Precautions
1. If you are using this to generate database queries, please at least use mysql_real_escape_string()
(e.g. mysql_real_escape_string($_POST['country'])
), unless you are using parametriezed queries (e.g. PDO or MySQLi).
2. If you are outputting the string to the user use htmlentities()
(e.g. htmlentities($_POST['country'])
).
$loc = array($_POST['country'], $_POST['state'], $_POST['city']);
echo implode(",", $loc);
精彩评论