Problem in array search
I am trying to find values inside an array. This array always starts with 0. unfortunat开发者_JS百科ely array_search start searching with the array element 1. So the first element is always overlooked.
How could I "shift" this array to start with 1, or make array-search start with 0? The array comes out of an XML web service, so I can not rally modify the results.
array_search
does not start searching at index 1. Try this example:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('blue', $array); // $key = 0
?>
Whatever the problem is with your code, it's not that it's first element is index 0.
It's more likely that you're use ==
instead of ===
to check the return value. If array_search returns 0, indicating the first element, the following code will not work:
// doesn't work when element 0 is matched!
if (false == array_search(...)) { ... }
Instead, you must check using ===
, which compares both value and type
// works, even when element 0 is matched
if (false === array_search(...)) { ... }
See the manual, it might help you: http://www.php.net/manual/en/function.array-search.php
If what you're trying to do is use increase the key by one, you can do:
function my_array_search($needle, $haystack, $strict=false) {
$key = array_search($needle, $haystack, $strict);
if (is_integer($key)) $key++;
return $key;
}
my_array_search($xml_service_array);
精彩评论