views:

50

answers:

3

I have an array that is formatted like so (this example has 5 keys):

[0]: HTTP/1.1 200 OK
[1]: Date: Wed, 10 Feb 2010 12:16:24 GMT
[2]: Server: Apache/2.2.3 (Red Hat)
[3]: X-Powered-By: PHP/5.1.6
[4]: etc..

The array keys sometimes alternate, as one may be omitted. How can I search for the array with "Server: ..." in it, and if it exists display it?

For the life of me I am confused!

+1  A: 

Try

array_search()Searches the array for a given value and returns the corresponding key if successful

You have to be a bit more specific about whether you want to search for a substring or an exact value, e.g. you want to search for "Server: Apache/2.2.3 (Red Hat)" or just anything with the substring "Server" in it. In the latter case, go with Gumbo's solution, as array_search cannot be used for substring searches.

Gordon
+3  A: 

The intuitive approach would be to iterate the array and test each item:

foreach ($array as $item) {
    if (strncasecmp(substr($item, 0, 7), 'Server:') === 0) {
        echo $item;
    }
}
Gumbo
+1  A: 

Try this:

 foreach($your_array as $value)
 {
  if (stripos($value, 'Server:') !== false)
  {
    echo $value;  // we found it !!
    break;
  }
 }
Sarfraz
What if `Server:` is not at the start of the string?
Gumbo
@Gumbo: it will still be found, i am using stripos, it find it where ever it is.
Sarfraz
@Gumbo: strpos function gives the location of the string whereever it is found, you know that :)
Sarfraz
@Sarfraz: Yes, and that’s the point. The asker probably just wants to print the value if it starts with `Server:`.
Gumbo
This is what I was looking for actually, It only can contain one string of 'Server:' and worked flawlessly. Thanks Sarfraz.
oni-kun
@oni-kun: you are welcome :)
Sarfraz