PHP:避免未定义的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5839726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Avoid undefined index?
提问by Gabriel
Every time a POST value is not equal to the list of values set in an array will return: Undefined Index error, I made an if statement but is not working.
每次 POST 值不等于数组中设置的值列表时,都会返回:未定义索引错误,我做了一个 if 语句但不起作用。
Here's the if statement:
下面是 if 语句:
if ($products[$_POST['product']] == $_POST['product']) {
do everything;}
else {
echo "This item is not available";
}
EDIT2:
编辑2:
Seen the current situation avoiding the warning wont help much because I'm dealing with several factors, for example a list of items in a Shopping Cart, if the invalid product is not removed, it will be added to the shopping list session.
看到当前情况避免警告不会有太大帮助,因为我正在处理几个因素,例如购物车中的项目列表,如果无效产品没有被删除,它将被添加到购物清单会话中。
This is the full script:
这是完整的脚本:
<?php
session_start();
//Getting the list
$_SESSION['list'] = isset($_SESSION['list']) ? $_SESSION['list'] : array();
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
if( isset($_POST['product']) ){
//Saving the stuff
$new_item = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
$new_product = true;
foreach($_SESSION['list'] as $key => $item) {
if ($item['item'] == $new_item['item']) {
$_SESSION['list'][$key]['quantity'] += $new_item['quantity'];
$_SESSION['list'][$key]['price'] = $products[$new_item['item']] * $new_item['quantity'];
$new_product = false;
}
}
if ($new_product) {
$_SESSION['list'][] = $new_item;
}
/*if ($new_item['item'] != $products[$new_item['item']]) {
echo "This item is not available";}*/
//listing
echo "<b>SHOPPING LIST</b></br>";
foreach($_SESSION['list'] as $key => $item) {
echo 'Product .'. $key. ' '. $item['item'], ' ', $item['quantity'], ' units: ', $item['price']. '<br />';
}
}
else {
echo "This item is not available";
}
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
session_destroy();
?>
回答by Dan Blows
I'm a bit confused by your code. It looks like your array has the same key and value, so:
我对你的代码有点困惑。看起来您的数组具有相同的键和值,因此:
$products['saucepan'] = 'saucepan'
Perhaps you are trying to do this, which will check whether the product exists in the products array:
也许您正在尝试这样做,这将检查产品是否存在于 products 数组中:
if(isset($_POST['product']) && array_key_exists($_POST['product'], $products))
{
// do stuff
}
else
{
echo "This item is not available";
}
回答by Garland Pope
With PHP 7, the null coalescing operatorcan be used to deal with optional request variables. You can change your $_POST['product']
reference to $_POST['product'] ?? null
which will resolve to null (rather than throwing the warning) if 'product' is not a valid key in the post array. If you wanted to check both the $_POST and $_GET arrays for a value, you would use $_POST['product'] ?? $_GET['product'] ?? null
.
在 PHP 7 中,空合并运算符可用于处理可选的请求变量。如果 'product' 不是 post 数组中的有效键,您可以更改将解析为 null(而不是抛出警告)的$_POST['product']
引用$_POST['product'] ?? null
。如果您想同时检查 $_POST 和 $_GET 数组的值,您可以使用$_POST['product'] ?? $_GET['product'] ?? null
.
回答by cmptrgeekken
回答by Cedric
@$_POST['product']
(with an @) will return the same thing as :
(带有@)将返回与以下相同的内容:
$product = (isset($_POST['product'])) ? $_POST['product'] : null;
Shorter is sweeter !!4 times less code ! Easier to read and understand.
越短越甜!!代码减少 4 倍!更容易阅读和理解。
The @ symbol is the error control operator (AKA the "silence" or "shut-up" operator). It makes PHP suppress any error messages (notice, warning, fatal, etc.).
@ 符号是错误控制操作符(又名“沉默”或“关闭”操作符)。它使 PHP 抑制任何错误消息(通知、警告、致命等)。
But beware not to use @ for any other thing, as it would make your code so much harder to debug!
但是请注意不要将@ 用于任何其他事情,因为它会使您的代码更难以调试!
(this will answer your question before the edit)
(这将在编辑之前回答您的问题)
回答by sunny
You could also try
你也可以试试
$product = (isset($_POST['product'])) ? $_POST['product'] : null;
This will set $product to the $_POST value if it exists, or to null if not. Then you could try
如果存在,这会将 $product 设置为 $_POST 值,否则设置为 null。那你可以试试
if ($product) {
do_something();
}
or access your array with
或访问您的阵列
$products[$product];
I feel this way it makes your code that little bit easier on the eyes..
我觉得这样可以让你的代码在眼睛上更容易一些..
回答by Etta EGBE JOSEPH
You can just use a ??
to set set a default value if your value is not set.
??
如果您的值未设置,您可以使用 a来设置默认值。
$_POST['product'] ?? "No product";
$_POST['product'] ?? "No product";
回答by Ibu
if (isset($products[$_POST['product']]) && $products[$_POST['product']] == $_POST['product'])
the isset() function will help you avoid the warning
isset() 函数将帮助您避免警告
回答by fatnjazzy
if(isset($products[$_POST['product']) && $products[$_POST['product'] != "")
Note that a vriable can be empty but also "set" so the what comes after the && is necessary.
请注意,变量可以为空,但也可以“设置”,因此 && 之后的内容是必要的。
回答by naiquevin
you can check whether the index 'product' is defined in the same if statement ..
您可以检查索引“产品”是否在同一个 if 语句中定义..
if (isset($_POST['product']) && $products[$_POST['product']] == $_POST['product']) {
do everything;
}
else {
echo "This item is not available";
}