gpt4 book ai didi

PHP 如果未定义,则在 GET 值上设置默认值

转载 作者:太空宇宙 更新时间:2023-11-04 14:17:03 25 4
gpt4 key购买 nike

我有下面的表格,我在我的字段中输入了一个不同的值,具体取决于是否有任何要获取的内容。

我的工作有效,但我想知道是否有更有效的编码方式,因为我的真实表单将有大约 10 个输入字段,我不想每次添加新的时都添加 6 行代码输入字段?

        <?php
if (isset($_GET["name"])) {
$name = $_GET["name"];
}
else {
$name = 0;
}

if (isset($_GET["type"])) {
$type = $_GET["type"];
}
else {
$type = 0;
}

if (isset($_GET["other"])) {
$other = $_GET["other"];
}
else {
$other = 0;
}
?>


<input type="text" name="name" value="<?php echo $name; ?>">
<input type="text" name="type" value="<?php echo $type; ?>">
<input type="text" name="other" value="<?php echo $other; ?>">

我也试过

        <?php
$name = $_GET["name"] ?: 0;
?>

这会在我的表单中输入 0 值,但我收到错误消息 Notice: Undefined index: name

最佳答案

在三元运算符中使用isset():

$name = isset($_GET["name"]) ? $_GET["name"] : 0;

您收到通知是因为您直接评估了 $_GET['name'],而没有使用 isset()empty() 包装器.

您可能更愿意创建一个 resuble 函数来简化您的代码:

function filterThing($key){
return isset($_GET[$key]) ? $_GET[$key] : 0;
}

$name = filterThing('name');
$type = filterThing('type');
$other = filterThing('other');

关于PHP 如果未定义,则在 GET 值上设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23310228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com