关联数组中的变量问题 [英] Problems with variables in associative arrays
问题描述
如果用户未填写该字段,我希望使用默认字符串作为关联数组的值。例如未插入。如果用户填写该字段,则变量应采用用户输入的值。所以我写了这段代码:
I would like to have default string as values of an associative array if a user didn't fill in the field. For example "not inserted". If a user fills in the field, a variable should take the value the user put. So I wrote this code:
<?php
if (isset($_POST['submit'])){
if (isset($_POST['name'])){
$name =$_POST['name'];
} else {
$name = "not inserted";
}
if (isset($_POST['surname'])){
$surname =$_POST['surname'];
} else {
$surname = "not inserted";
}
if (isset($_POST['job'])) {
$job = $_POST['job'];
} else {
$job = "not inserted";
}
$data = array('name'=>$name, 'surname'=>$surname, 'job'=>$job);
print_r($data);
}
?>
<form action="" method="post">
<input type="text" id="name" name="name"/>
<input type="text" id="surname" name="surname"/>
<input type="text" id="job" name="job"/>
<input type="submit" id="submit" name="submit"/>
</form>
但是如果我不填写某些字段而不是未插入,则字符串print_r向我显示以下结果:
But if I don't fill in some field instead of "not inserted" string print_r shows me the following result:
Array ( [name] => [surname] => [job] => )
请,有人可以告诉我我哪里出错了吗?谢谢。
Please, can someone tell me where did I go wrong? Thanks.
推荐答案
空白输入仍会张贴到表单操作页面上,即使它们没有内容。因此,如果在所有字段都保留为空的情况下使用 var_dump($ _ POST)
,您会看到类似以下内容:
Blank inputs are still posted to a forms action page, even if they have no content. So if you were to var_dump($_POST)
when leaving all your fields empty, you'd see something like this:
array (size=3)
'name' => string '' (length=0)
'surname' => string '' (length=0)
'job' => string '' (length=0)
...
它们是设置(即它们存在)但为空。您可以使用 empty()
函数检查其中是否存在值:
They are set (i.e. they exist) but are empty. You can check if there is a value in there using the empty()
function like this:
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = "not inserted";
}
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = "not inserted";
}
if (!empty($_POST['job'])) {
$name = $_POST['job'];
} else {
$name = "not inserted";
}
详细了解如何空
在文档中起作用。
Read more about how empty
works in the documentation.
这篇关于关联数组中的变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!