Jump to content

[SOLVED] Search a string for an object within an array


axelheyst

Recommended Posts

Is there a way to use a search function (stripos) such that:

$num=stripos($haystack,$needle);

where $needle is an array like:

$needle=array('red','blue','green');

Basically, I would like to know if $haystack contains any of these items. It would also be nice to know which item is contained in $haystack, and the start position of this item $needle[0] or $needle[1].

Any thoughts? Thank you all!
[code]foreach($haystack AS $hay){
  foreach($needle AS $ow){
      if($stripos($hay, $ow) !== FALSE){
          print $hay.' contains: '.$ow.' at '.$stripos($hay, $ow).'<br />;
      }
  }
}
[/code]
(not tested)

Edit: is $haystack an array also? If it's not, just take out the first foreach, change to:
[code]
  foreach($needle AS $ow){
      if($stripos($haystack, $ow) !== FALSE){
          print $haystack.' contains: '.$ow.' at '.$stripos($haystack, $ow).'<br />;
      }
  }
[/code]
If I'm reading this right it sounds like you want
[url=http://au3.php.net/manual/en/function.in-array.php]http://au3.php.net/manual/en/function.in-array.php[/url] - returns bool or
[url=http://au3.php.net/manual/en/function.array-search.php]http://au3.php.net/manual/en/function.array-search.php[/url] - returns key or false if not found

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.