Get the index value of an array in PHP

后端 未结 12 2032
迷失自我
迷失自我 2020-12-04 23:05

I have an array:

$list = array(\'string1\', \'string2\', \'string3\');

I want to get the index for a given value (i.e. 1 for <

12条回答
  •  情书的邮戳
    2020-12-04 23:37

    array_search is the way to do it.

    array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

    From the docs:

    $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
    
    $key = array_search('green', $array); // $key = 2;
    $key = array_search('red', $array);   // $key = 1;
    

    You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

提交回复
热议问题