2

In order to check if a substring is present in a string:

if (strpos($haystack,$needle)!==false) {...}

But need to check if any array value contains a string.

For ex: check if "oran" is contained in any value of $arr

$arr=array('orange1','orange2','orange3')

Always can do foreach and analysze every array value with strpos.

But is there an elegant and nice alternative?

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
ihtus
  • 2,673
  • 13
  • 40
  • 58
  • 1
    There's no built-in function to do this AFAIK. The `foreach` loop is probably best. You could use `array_filter()`, but with `foreach` you can stop at the first match instead of checking every element. – Barmar Oct 31 '13 at 20:51
  • 1
    http://us3.php.net/preg_grep – nice ass Oct 31 '13 at 20:54
  • Try preg_grep, an older post has examples at http://stackoverflow.com/questions/8627334/how-to-search-in-array-with-preg-match – keenydev Oct 31 '13 at 21:02

2 Answers2

3

How about this?

if(strpos(implode(' ', $arr), 'oran') !== false){...}

You need the space separator so you don't accidentally do:

$arr = array('for', 'antlr');  // implode would make 'forantlr', which contains 'oran'
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • Seems like a horrible 'solution' to a non-existent problem. Just use a loop. – Supericy Oct 31 '13 at 20:54
  • @Supericy Explain why this is horrible. Also, op stated he's aware of how to use a loop, and is looking for an *alternative*. This is that. What's more, this is very likely faster than using a loop. – Madbreaks Oct 31 '13 at 20:56
  • How would this at all be faster than just using a loop? You're building an massive string (doubling the amount of memory you use), which requires looping through the entire array anyway. You do answer the question though (even though now you can't use a space in the needle), so perhaps my comment should have been on the question rather than your answer. – Supericy Oct 31 '13 at 20:58
  • With a loop you can break on match, while with your code you would have to read entire array all the time – nice ass Oct 31 '13 at 20:59
  • Bad example, but what if your `$needle` was "abc, 123;"? Now you need to change the delimiter to something that isn't in the needle. But the loop should be more efficient as you can stop when you find a match (rather than building a (possibly large) string). – Matt Oct 31 '13 at 20:59
  • If it were me I would *just use a loop*. Op asked for an alternative. So shoot me. – Madbreaks Oct 31 '13 at 21:00
  • @Supericy I recant my claim that it's probably faster after thinking about it further. As for the "can't use a space needle" (ha) that's true, though one could probably work around it. Oh well. – Madbreaks Oct 31 '13 at 21:03
1
foreach ($arr as $a) {
   if (strpos($a,'oran') !== false) { ... }
}

I know we're all thinking this anyways. /thread.

blegh
  • 11
  • 1