“固定”;未定义索引“;PHP中的错误
它显示“固定”;未定义索引“;PHP中的错误,php,Php,它显示注意:未定义的索引:月份在…. 我知道如果我使用错误报告(null)在代码上方,通知将不会出现,但是否有方法修复此错误?您必须使用empty()或isset()检查是否定义了变量 if ((!$_GET['month']) && (!$_GET['year'])) { $month = date ("n"); $year = date ("Y"); } else { $month = $_GET['month']; $year = $_GET['year']
注意:未定义的索引:月份在….
我知道如果我使用
错误报告(null)代码>在代码上方,通知将不会出现,但是否有方法修复此错误?您必须使用empty()
或isset()
检查是否定义了变量
if ((!$_GET['month']) && (!$_GET['year'])) {
$month = date ("n");
$year = date ("Y");
} else {
$month = $_GET['month'];
$year = $_GET['year'];
}
如果数组元素不存在,则会收到通知,因为您试图访问一个不存在的元素。您需要使用或检查它(这些不是函数,而是语言构造,因此不考虑访问这些元素)。因为你可能从来没有空的/零年/月,empty
更有意义;但是你也可以使用!isset()
,则也允许使用0
和空字符串
if ( empty($_GET['month']) || empty($_GET['year']) ) {
$month = date ("n");
$year = date ("Y");
} else {
$month = $_GET['month'];
$year = $_GET['year'];
}
但是,单独检查这两个变量可能更有意义:
if(empty($_GET['month']) || empty($_GET['year'])) {
$month = date('n');
$year = date('Y');
}
else {
$month = (int)$_GET['month'];
$year = (int)$_GET['year'];
}
是的,您可以在if块中使用if(isset($\u GET['month'])和&isset($\u GET['year'])
,当前的方法是同时检查这两个参数,如果其中一个未能同时更改这两个参数,则最好先预设月份和日期,然后在通过参数时更改。另外,最好在那里检查一下。否则,字符串可能会进一步破坏代码
$month = date('n');
$year = date('Y');
if (isset($_GET['month'])) {
$month=$_GET['month'];
}
if (isset($_GET['year'])) {
$year=$_GET['year'];
}
检查您的逻辑。如果月是空的而不是年呢?砰。未定义的索引“月”。isset
array\u key\u存在
和empty
是您的朋友。可能是重复的,我一发布它就意识到了。我仍然有一个问题。如果同时设置了月份和年份,则仅设置月份。(第3行和第5行显示如何正确执行他想要的逻辑的不匹配的(
)可能是好的。如果(!empty(…)&!(empty(…){$month=…;$year=…}否则{$month=date('n');$year=date('Y');}
$month=empty(intval($\u GET['month'])))(date n'):$\u GET['month'];@askovpen intval始终返回至少(int)所以它永远不会是empty@Corbin:是的,但我非常怀疑他是否希望这样做,因为如果只有一个值丢失,这仍然会给他留下通知。按照我编写的方式,该代码块不可能为未定义的索引生成通知。要么两个索引都已定义,要么两个索引都未访问。
$month = date('n');
$year = date('Y');
if (isset($_GET['month'])) {
$month=$_GET['month'];
}
if (isset($_GET['year'])) {
$year=$_GET['year'];
}
<?php
$month = date ("n");
$year = date ("Y");
if (isset($_GET['month']) && is_numeric($_GET['month'])) {
$month = $_GET['month'];
}
if (isset($_GET['year']) && is_numeric($_GET['year'])) {
$year = $_GET['year'];
}
//Or better yet
$month = (isset($_GET['month']) && is_numeric($_GET['month']))?$_GET['month']:date("n");
$year = (isset($_GET['year']) && is_numeric($_GET['year']))?$_GET['year']:date("Y");
?>