简体   繁体   English

PHP使用三元运算符的未定义索引

[英]PHP Undefined index using ternary operator

my PHP version is 5.3.5. 我的PHP版本是5.3.5。

The code: 编码:

$num = $_REQUEST['num'] ?: 7;

The error: 错误:

Notice: Undefined index: num in C:\path\to\file.php on line 34

Any suggestions? 有什么建议么?

$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : 7;

我假设你想要$_REQUEST['num'] ,否则设置为7。

Isn't using error suppression for short assignment code good ?. 是不是对短分配代码使用错误抑制好?

we can write $price = @$rec['Product']['new'] ?: $rec['Product']['old']; 我们可以写$ price = @ $ rec ['Product'] ['new']?:$ rec ['Product'] ['old'];

Using @ saved me from repeating of same variable and allowed me to use short cut ternary operator without generating notice. 使用@保存我重复相同的变量,并允许我使用捷径三元运算符而不产生通知。

I know using @ is considered not good but for this particular case, I don't imagine anything could go wrong ever. 我知道使用@被认为不好,但对于这种特殊情况,我不认为任何事情都可能出错。

Thanks. 谢谢。

This is expected behavior; 这是预期的行为; according to http://bugs.php.net/bug.php?id=45760 , the ?: shortcut is just that: a shortcut. 根据http ?: //bugs.php.net/bug.php ?: id=45760?:快捷方式就是:快捷方式。

In other words: 换一种说法:

$num = $_REQUEST['num'] ?: 7;

is evaluated identically to: 的评估方式与:

$num = $_REQUEST['num'] ? $_REQUEST['num'] : 7;

and everything that implies (and is addressed quite adequately by the other answers in the thread). 以及所暗示的一切(并且通过线程中的其他答案得到充分解决)。

If it isn't in the request, you may get a warning. 如果它不在请求中,您可能会收到警告。

You're better off doing this: 你最好这样做:

$num = (array_key_exists('num', $_REQUEST)) ? intval($_REQUEST['num']) : 7;

I second dhaval solution of using @ error suppression, what is more readable: 我使用@ error suppress的第二个dhaval解决方案,更具可读性:

$num = @$_REQUEST['num'] ?: 7; $ num = @ $ _ REQUEST ['num']?:7;

..or.. ..要么..

$num = (array_key_exists('num', $_REQUEST)) ? $ num =(array_key_exists('num',$ _REQUEST))? $_REQUEST['num'] : 7; $ _REQUEST ['num']:7;

I know which I would prefer to read if I was trying to understand someone else's code. 如果我试图了解别人的代码,我知道我更愿意阅读哪些内容。 I think it provides the happy medium between setting error_reporting to E_ALL & ~E_NOTICE (very bad) and the boilerplate code above. 我认为它提供了设置error_reporting到E_ALL和~E_NOTICE(非常糟糕)和上面的样板代码之间的愉快介质。

$num = (isset($_REQUEST['num'])) ? $_REQUEST['num'] : 7;

Accessing an array with an index that doesn't exist is always going to throw a notice. 访问具有不存在的索引的数组总是会引发注意。 You need to either ignore the notice since that does return null, or technically you're supposed to use array_key_exists . 你需要忽略通知,因为它确实返回null,或者技术上你应该使用array_key_exists

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM