简体   繁体   中英

check if string exists in array element

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM