Srinivas Srinivas - 4 months ago 9
PHP Question

How to search array item with given string

i have an array:

$mainArr = ["SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS"];

$strArr = ["SRI"];


i want to search the main Array with the given string Array element so that if the string is matched it should get the corresponding key,value pair.

expected o/p would be:

Array[
0->SRI
3->SRI#AIS
4->SRI#GOW
5->SRI#AIS#GOW
]


Any ideas ?

Thanks,
Srinivas

Answer
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");

$strArr = array("SRI");
foreach ($mainArr as $key => $value)
{
    foreach ($strArr as $str)
    {
        if (strpos($value,$str) !== false) $rez[$key] = $value;
    }
}

var_dump($rez);

output:

    array(4) { 
[0]=> string(3) "SRI" 
[3]=> string(7) "SRI#AIS" 
[4]=> string(7) "SRI#GOW" 
[5]=> string(11) "SRI#GOW#AIS" 
}