当从表单发布null变量时,更简洁地表达if-else语句


Expressing if else statements more succintly when null variable is posted from form

有更好的方法来表达这个PHP代码吗?我已经从表单中收到了变量,现在需要在输出文本字符串之前检查它们是否为null。

非常感谢!

$Capacity = $_POST["Capacity"];
$Location = $_POST["Location"];
$RoomType = $_POST["RoomType"];
echo '<div id="container" style="padding: 15px; background-color: #949494;">';
echo '<div style="padding: 15px; background-color: #fff;">';
echo '<h2>Search results:</h2>';
echo '<h3>Showing';
if ($RoomType == '') echo ''; else echo ' '.$RoomType.' ';
echo ' rooms with a capacity of '. $Capacity .' and over';
if ($Location == '') echo ''; else echo ' in  '.$Location.' Park';
echo '</h3>';

编辑2:我重新访问了代码,使其更有意义。

<?php
$requiredFields = array(
    'Capacity',
    'Location',
    'RoomType'
);
// Retrieve only the allowed fields
$fields = array_intersect_key($_POST, array_flip($requiredFields));
// Remove whitespace
$fields = array_map('trim', $fields);
// Remove empty values
$fields = array_filter($fields, 'strlen');
// Filter values for HTML output
$fields = array_map('htmlentities', $fields);
// We require all fields
if(count($fields) !== count($requiredFields)) {
    exit('Your browser sent incorrect data!');
}
// Create the variables
extract($fields, EXTR_SKIP);
?>
<h2>Search Results</h2>
<h3><?php printf('Showing %s rooms with a capacity of %s and over in %s Park', $RoomType, $Capacity, $Location) ?></h3>

编辑:添加htmlentities过滤器

/* Safely retrieve input parameters */
$Capacity = filter_input(INPUT_POST, 'Capacity', FILTER_SANITIZE_SPECIAL_CHARS);
$Location = filter_input(INPUT_POST, 'Location', FILTER_SANITIZE_SPECIAL_CHARS);
$RoomType = filter_input(INPUT_POST, 'RoomType', FILTER_SANITIZE_SPECIAL_CHARS);
/* Define html template */
$tmpl = <<<EOFHTML
<div id="container" style="padding: 15px; background-color: #949494;">
<div style="padding: 15px; background-color: #fff;">
<h2>Search results:</h2>
<h3>Showing %s rooms with a capacity of %s and over %s
</h3>
EOFHTML;
/* Output result */
if( !empty($Location)) $Location = ' in '.$Location.' Park ';
printf( $tmpl, $RoomType, $Capacity, $Location);

您可以使用"三元运算符"。它之所以被称为三元运算符,是因为它需要三个操作数(不像"加号",它是一个需要两个操作数的二进制运算符)。撇开操作数不谈,它的工作原理与类似

some true/false expression   ?   result when true  :  result when false

从你的例子:

echo ($RoomType == '') ? '' : ' '.$RoomType.' ';

我认为这样检查没有意义

$Capacity = htmlspecialchars($_POST["Capacity"]);
$Location = htmlspecialchars($_POST["Location"]);
$RoomType = htmlspecialchars($_POST["RoomType"]);
echo "<div id='container' style='padding: 15px; background-color: #949494;'>
<div style='padding: 15px; background-color: #fff;'>
<h2>Search results:</h2>
<h3>Showing $RoomType rooms with a capacity of $Capacity and over in  $Location Park</h3>";

还好。