Get the index value of an array in PHP

后端 未结 12 2034
迷失自我
迷失自我 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:25

    Other folks have suggested array_search() which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values():

    $list = array(0=>'string1', 'foo'=>'string2', 42=>'string3');
    $index = array_search('string2', array_values($list));
    print "$index\n";
    
    // result: 1
    

    You said in your question that array_search() was no use. Can you explain why? What did you try and how did it not meet your needs?

提交回复
热议问题