0

Is there any function that can do what strpos does, but on the elements of an array ? for example I have this array :

    Array
(
 [0] => a66,b30
 [1] => b30
)

each element of the array can contain a set of strings, separated by commas.

Let's say i'm looking for b30. I want that function to browse the array and return 0 and 1. can you help please ? the function has to do the oppsite of what this function does.

Community
  • 1
  • 1
RidRoid
  • 961
  • 3
  • 16
  • 39
  • well, what have you tried so far? you know we expect that you try something. Show some code. – CodeGodie Aug 05 '15 at 13:59
  • 1
    `$check = 'b30'; $result = array_filter($myArray, function ($value) use ($check) { return strpos($value, $check) !== false; } );` – Mark Baker Aug 05 '15 at 14:00
  • When you say : " I want that function to browse the array and return 0 and 1" , you mean 1 for each array containing the string, or if one if there is at least 1 array containing the string ? – Peut22 Aug 05 '15 at 14:01
  • @CodeGodie I tried the `in_array` function but it did not work (need to split what's on the element first) – RidRoid Aug 05 '15 at 14:02
  • have you tried `explode`? – CodeGodie Aug 05 '15 at 14:04
  • i can indeed use explode and then read from the result...but with every element of my initial array i will have an array of exploded values. i'm looking for a fancier way :) – RidRoid Aug 05 '15 at 14:13
  • @MarkBaker +1 thanks ! those two tiny lines of code do exactly what i wanted. please answer my question so i can accept it. – RidRoid Aug 05 '15 at 14:25

2 Answers2

0

Try this (not tested) :

function arraySearch($array, $search) {
    if(!is_array($array)) {
        return 0;
    }
    if(is_array($search) || is_object($search)) {
        return 0;
    }
    foreach($array as $k => $v) {
        if(is_array($v) || is_object($v)) {
            continue;
        }
        if(strpos($v, $search) !== false) {
            return 1;
        }
    }
    return 0;
}
Jeremy
  • 111
  • 1
  • 9
0

You could also use preg_grep for this.

<?php

$a = array(
 'j98',
 'a66,b30',
 'b30',
 'something',
 'a40'
);

print_r( count(preg_grep('/(^|,)(b30)(,|$)/', $a)) ? 1 : 0 );

https://eval.in/412598

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49