Reputation: 33956
I want to find the first occurrence of any of several values in an array.
$sentence = array(I, want, to, go, to, the, market);
if(in_array(array('swim','fly','go'), $sentence)) {
// Should return KEY = 3 as 'go' was found in the third key of the array
}
I'm sure this must be fairly common, how can it be done?
Upvotes: 1
Views: 111
Reputation: 33956
function find_in_array($needles,$array) {
$pos = false;
foreach ($needles as $key => $value) {
if (in_array($value, $array)) {
if(!$pos || array_search($value, $array) < $pos) {
$pos = array_search($value, $array);
}
}
}
return $pos;
}
echo find_in_array($values,$sentence);
This is what I am using right now, I'm testing array_keys as suggested by Darian Brown
Upvotes: 0
Reputation: 3065
first of all you should read manual properly of in_array function , you were passing parameters in wrong order
$sentence = array(I, want, to, go, to, the, market);
$found_key = array();
foreach($sentence as $key => $word)
{
if(in_array($word,array('swim','fly','go')))
{ $found_keys[] = $key;}
}
print_r($found_keys);
I hope this is what you need
Upvotes: 0
Reputation: 168
array_keys would work a treat.
$keys = array_keys($sentence,array('swim','fly','go');
Then $keys will be a list of keys where swim, fly and go appear in $sentence
Just as the code below will return a list of keys that have empty values
$array = array('one','','three');
$keys = array_keys($array,"");
Upvotes: 0
Reputation: 5331
http://tr.php.net/manual/en/function.array-keys.php
I think more specifically you are looking for this type of functionality?
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
The above example will output:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)
Upvotes: 1
Reputation: 2129
Please use this function array_search it will return key of the element if element found in the array
Example
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
Upvotes: 0