PHP Find Array Index value in multi-line array

You can use foreach and check as:

  1. You can convert comma separated string to array, and check using in_aray
  2. if that value found, then you can fill in new output array.

See below example

$array1['Alpha']="New York,Los Angeles,Washington";
$array1['Beta']="New York,Los Angeles,Honolulu";
$array1['Gamma']="New York,Los Angeles,Washington";

$returnData = [];
foreach ($array1 as $k => $val)
{
 $datas = explode(",",$val);
    if(in_array('Washington', $datas) ){
        $returnData[] = $k;
    }
}

print_r($returnData);

Output will be: [0] => Alpha [1] => Gamma


It's because array_search looks for full match.

Simply loop array and check existence of search string:

$array1['Alpha']="New York,Los Angeles,Washington";
$array1['Beta']="New York,Los Angeles,Honolulu";
$array1['Gamma']="New York,Los Angeles,Washington";

$keyword = 'Washington';

foreach ($array1 as $key => $cities)
{
   if (str_contains($cities, $keyword)) {
        echo $key . "\n";
   }
}

Example


I don't know if it's the most efficient way, but you could use array_filter() (doc) to acheive this.

Example :

<?php
$array['Alpha']="New York,Los Angeles,Washington";
$array['Beta']="New York,Los Angeles,Honolulu";
$array['Gamma']="New York,Los Angeles,Washington";
$search = "Washington";

$result = array_keys(array_filter($array, function($a) use ($search) {
    return strpos($a, $search) > -1;
}));

print_r($result);

Where the function is an anonymous function (so could be changed), will display:

Array
(
    [0] => Alpha
    [1] => Gamma
)