5

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.

1
  • Maybe you should show your code and how you search because obviously array_search works correct But maybe it is not the right function for your purpose. Commented Feb 1, 2010 at 20:52

2 Answers 2

14

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(...)) { ... }
Sign up to request clarification or add additional context in comments.

2 Comments

wow thanx buddy that was awesome , i think i find out the problem .
At it is said in this big red warning box on this site: php.net/manual/en/function.array-search.php Reading manual pages sometimes really helps!
3

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);

3 Comments

hmm thanx but can u explain more because i used Zero but not working . does array_search() start at the 0 key ?
sure the index key is Zero , look down at what meagar said as an example
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.