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!
Link to comment
Share on other sites

[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]
Link to comment
Share on other sites

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.