0

我正在尝试在与字符串匹配的数组中查找键号。

我以这种方式尝试了array_search

$key = array_search("foo", $array);
echo $array[$key];

但这会打印 $array[0]

还有另一种方法可以做到这一点吗?

谢谢 :)

4

2 回答 2

2

如果未找到密钥,则array_search返回false。你必须检查一下(下面我的例子中的第 3 行)

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search("green", $array); //the $key will be "2"
if ($key !== false) {
   echo $array[$key];
}

否则,您的代码似乎可以满足您的需求。如果有问题,请发布更多代码。

于 2010-01-03T07:44:40.280 回答
0

I'm not exactly matching the whole string, just one part, will array_search still work?

btw i made a loop through the array with for each that do a preg_match until it finds the string then breaks the loop and store the key in a array

于 2010-01-04T02:15:54.497 回答