Reputation: 844
I have some troubles finding the right key in an array:
when I have an array: $haystack
$haystack = array(0 => 'apple',
1 => 'apple',
2 => 'pear',
3 => 'apple',
4 => 'banana');
and is use the function array_search
$key = array_search('apple', $haystack);
the function wil set the $key value to '0' ( $key = 0 )
I need to find the key of the fourth item in the array (3) which is also apple... Does anyone know a function that searches the array from a given index and returns a value?
for example something like:
array_search_start($needle, $haystack, $startPosition);
Upvotes: 0
Views: 4676
Reputation: 1770
This will be so easy to use
$haystack = array(0 => 'apple',
1 => 'apple',
2 => 'pear',
3 => 'apple',
4 => 'banana');
$keys = array_keys($haystack,'apple');
foreach($keys as $k):
$searchK[] = $haystack[$k];
endforeach;
print_r($searchK);
Upvotes: 0
Reputation: 326
$haystack = array(0 => 'apple',
1 => 'apple',
2 => 'pear',
3 => 'apple',
4 => 'banana');
$find = 'apple';
foreach ($haystack as $k=>$v) {
if($find == $v) {
echo 'found! key is '.$k.'<br />';
}
}
Upvotes: 0
Reputation: 193261
Use array_keys
with the second parameter to specify value to search keys for.
$keys = array_keys($haystack, 'apple');
So $keys
will contain array of found keys corresponding to search value (apple
):
Array
(
[0] => 0
[1] => 1
[2] => 3
)
Now you can get the last one, or the first, etc. If you need the last:
$key = end($keys);
Upvotes: 4
Reputation: 592
<?
$array = array("one"=>'paul',"two"=>'lady');
print_r(array_values($array));
?>
Upvotes: 0
Reputation: 6335
You can use array_keys
to get all keys with values apple
$keys = array_keys($haystack, 'apple');
if you need it to write as a function then you can do:
$searchValue = 'apple';
$keys = searchKeys($haystack, $searchValue);
function searchKeys($haystack,$searchValue) {
$keys = array_keys($haystack, $searchValue);
return $keys;
}
Hope this helps you :)
Upvotes: 0
Reputation: 2364
Don't know much about PHP but, couldn't you just include an offset as the start position?
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
So, in your case you would do
$key = array_search('apple', $haystack, 2);
Upvotes: 0
Reputation: 14479
You can also use array_slice to do this more simply than looping:
<?php
$key = array_search($needle, array_slice($haystack, $startPosition,-1,true));
?>
This syntax requires PHP>=5.0.2, as we need to preserve the keys (hence the -1
(no length limit) and true
which keeps the original keys)
Upvotes: 0
Reputation: 9007
This should work:
<?php
function array_search_start($needle, $haystack, $start) {
for ($i = $start; $i < length($haystack); $i++)
if ($haystack[$i] == $needle) return $i;
return FALSE; // You'll need === operator to distinguish between False and 0
}
?>
Good luck!
Upvotes: 0