Php 数组搜索不';如果键为1,则不返回结果
我有一个会话数组,我在其中存储了一些值,我打印了这些值——一切正常。然后我试着打印钥匙。当键为0、2、3等时返回结果,但如果键为1,则不会返回结果,即使它确实存在并且确实有关联的值Php 数组搜索不';如果键为1,则不返回结果,php,arrays,function,search,key,Php,Arrays,Function,Search,Key,我有一个会话数组,我在其中存储了一些值,我打印了这些值——一切正常。然后我试着打印钥匙。当键为0、2、3等时返回结果,但如果键为1,则不会返回结果,即使它确实存在并且确实有关联的值 if(isset($_GET['sterge'])) { $get=$_GET['sterge']; $key=array_search($get, $_SESSION['produse']); echo $key; //prints 0 if i set $get for the first
if(isset($_GET['sterge']))
{
$get=$_GET['sterge'];
$key=array_search($get, $_SESSION['produse']);
echo $key; //prints 0 if i set $get for the first element in the array, prints nothing if i set the second element, prints 2 for third element and so on...
}
如果使用键1打印元素,则得到预期结果。所以我不知道该看什么/去哪里
L.E。
$\u GET['sterge']来自下一行(以防万一)
foreach($\u会话['produse']作为$elm)
echo$elm.“
”;
…在调用数组_search()之前写入。所以,我按下“Sterge”,然后如果(isset$\u GET)执行,我只想打印这些键,看看它是否真的得到了它们。。
另外,var_dump($_SESSION['produse'])精确地打印出我期望它打印的内容,键1实际上有一个值(期望值),但出于某种原因,array_search()告诉键1的值“没有键”
最后一次编辑:一切都是由于我注意力不够引起的。特定值的末尾有一个空格,因此它与在array_search()函数中传递的值不同 如果在数组中找到针,则返回针的键,否则返回FALSE。当返回值为false时,echo$key将打印0。。。
您可以检查给定数组中是否有具有该名称的键,如下所示:
if(array_search($key, $array) !== false){echo $key;}else{echo "Key not found";}
确保已设置会话密钥。还要检查会话是否在试图访问$\u会话数组及其变量的每个文件上正确启动。用于调试所有内容并检查是否启用了错误报告:
如果这没有帮助,请使用更多信息更新您的问题,并尝试更好地解释您的问题(添加带有变量var_dump结果的相关代码)
要启用错误报告,只需添加类似error\u reporting(E\u ALL)的内容即可代码>在php脚本的开头。下面是一个关于指定不同错误级别报告的示例:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
错误报告处于打开状态(未显示任何内容),会话启动处于打开状态,数组中有元素,并且在使用var\u dump时这些元素被“转储”,但如果键为1,则返回“key not found”…您能用var\u dump的结果更新您的问题吗($\u会话['produse')?谢谢您的时间!不客气!祝你今天愉快:)
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>