开发者

PHP: How do I search in an unindexed array?

开发者 https://www.devze.com 2022-12-20 05:21 出处:网络
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

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: P开发者_Go百科HP/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!


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


Try this:

 foreach($your_array as $value)
 {
  if (stripos($value, 'Server:') !== false)
  {
    echo $value;  // we found it !!
    break;
  }
 }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消