查看 Paolo 的答案以了解三元运算符。
要执行您正在做的事情,您可能需要使用会话变量。
在页面顶部放置这个(因为在开始会话之前您无法向页面输出任何内容。IE NO ECHO STATEMENTS)
session_start();
然后,当用户提交您的表单时,将结果保存在此服务器变量中。如果这是用户第一次提交表单,直接保存即可,否则循环并添加任何不为空的值。看看这是不是你要找的:
HTML 代码 (testform.html):
<html>
<body>
<form name="someForm" action="process.php" method="POST">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input type="submit">
</form>
</body>
</html>
处理代码(process.php):
<?php
session_start();
if(!$_SESSION['items']) {
// If this is the first time the user submitted the form,
// set what they put in to the master list which is $_SESSION['items'].
$_SESSION['items'] = $_POST['items'];
}
else {
// If the user has submitted items before...
// Then we want to replace any fields they changed with the changed value
// and leave the blank ones with what they previously gave us.
foreach ($_POST['items'] as $key => $value) {
if ($value != '') { // So long as the field is not blank
$_SESSION['items'][$key] = $value;
}
}
}
// Displaying the array.
foreach ($_SESSION['items'] as $k => $v) {
echo $v,'<br>';
}
?>