Arrays are good for this:
$str = array();
foreach (array('first','second','third','fourth') as $k) {
if (isset($_POST[$k]) && $_POST[$k]) {
$str[] = $_POST[$k];
}
}
$last = array_pop($str);
echo implode(", ", $str) . " and " . $last;
You should probably have a special case above when there is one element. I actually wrote a function called "connection" that does the above and includes a special case:
function conjunction($x, $c="or")
{
if (count($x) <= 1) {
return implode("", $x);
}
$ll = array_pop($x);
return implode(", ", $x) . " $c $ll";
}
Good question!
: :
function and_form_fields($fields)
{
$str = array();
foreach ($fields as $k) {
if (array_key_exists($k, $_POST) && $v = trim($_POST[$k])) {
$str[] = $v;
}
}
return conjunction($str, "and");
}
...
and_form_fields(array("Name_1","Name_2",...));
$ _POST, .