Get the index value of an array in PHP

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

    If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

    $list = array('string1', 'string2', 'string3');
    $k = array_search('string2', $list); //$k = 1;
    

    If you want all (or a lot of them), a loop will prob do you better:

    foreach ($list as $key => $value) {
        echo $value . " in " . $key . ", ";
    }
    // Prints "string1 in 0, string2 in 1, string3 in 2, "
    

提交回复
热议问题