开发者

How to search an array key by matching a string in it's value

I'm trying to find the key number in a array matching a string.

I tried array_search in this way

$key = array_search("foo", $array);
ech开发者_如何学Goo $array[$key];

but that prints $array[0]

Is there another way to do this?

Thanks :)


If the key is not found, array_search returns false. You have to check for that (line 3 in my example below)

$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];
}

Otherwise, your code seems to do what you need. If there is a problem, please, post more code.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜