Get the index of a certain value in an array in PHP
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.
The problem is that you don't have a numerical index on your array.
Using array_values() will create a zero indexed array that you can then search using array_search() bypassing the need to use a for loop.
$list = ['string1', 'string2', 'string3'];
$index = array_search('string2',array_values($list));
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, "
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?