Array_search出现故障?

时间:2012-07-25 06:05:10

标签: php arrays search indexing return

前几行只是为了仔细检查所有变量是否符合要求。他们都提供了正确的数据。

print_r($ stack)确实给出了上面提到的数组元素(+和更多元素)

<?php
$item_name = $_POST['item_name']; 
echo $item_name.'<br/><br/>'; // IBM-3246785
print_r($stack);   // Array ( [0] => IBM-3246785 [1] => IBM-3567465 [2] => IBM-4579645 [3] => [4] => IBM-1234567 [5] => [6] => IBM-12345678 [7] => [8] => IBM-24374365 )            

$key = array_search($item_name, $stack);
if ($key !== false) {
    echo "The key where find was found is:" . $key;
} else{
    echo $item_name . " was NOT FOUND in the array";
};
?>

数组搜索返回false EVERYTIME !!! 尝试用IBM-3246785替换$ item_name - 问题仍然存在。 无法让它返回所选“item_name”的索引/键。

2 个答案:

答案 0 :(得分:2)

我刚刚在这里运行了这段代码---

<?php

$item_name = "IBM-3246785";
$stack = Array (0 => 'IBM-3246785', 1 => 'IBM-3567465', 2 => 'IBM-4579645', 3 => 'IBM-1234567',4 => 'IBM-12345678', 5 => 'IBM-24374365');


$key = array_search($item_name, $stack);
if ($key !== false) {
    echo "The key where find was found is:" . $key;
} else{
    echo $item_name . " was NOT FOUND in the array";
};
?>

并返回 - 找到find的关键是:0

答案 1 :(得分:0)

您可以尝试比较$ item_name和$ stack [0],例如if ($item_name == $stack[0]) echo "Done"; 您可以先尝试检查错误,例如if ($key === false) echo "Not"; else echo "Is"; 也许你可以尝试不同的功能来检索正确的数组密钥。