tags:

views:

127

answers:

2

I am trying to find values inside an array. This array always starts with 0. unfortunately 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.

+2  A: 

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);
farshad Ghazanfari
hmm thanx but can u explain more because i used Zero but not working . does array_search() start at the 0 key ?
Mac Taylor
sure the index key is Zero , look down at what meagar said as an example
farshad Ghazanfari
This example technically will solve your problem, but the resulting key will point 1 past the element you want to find. You'll still be finding element 0 though. Thus the key it returns won't actually tell you where to find the data.
meagar
+9  A: 

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(...)) { ... }
meagar
wow thanx buddy that was awesome , i think i find out the problem .
Mac Taylor
At it is said in this big red **warning** box on this site: http://php.net/manual/en/function.array-search.php Reading manual pages sometimes really helps!
Felix Kling