'PHP Find Array Index value in multi-line array

I have a multi-line array value setup in existing code (written by an former team member) as follows:

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

My need is that I have the value of a city (say "Washington"), and I need to get all the array index values which have Washington in their CSV list. So in the above case, the answer would be "Alpha" and "Gamma" (but not "Beta" as it does not contain Washington)

I tried array_search function, like

echo array_search("Washington",$array1);

but it is not yielding the desired result.

What am I missing here please?

Also tried

$cittskarray = explode(',', $array1["Washington"]);

foreach ($array1 as $cityvalue)
{
 ;//search one by one
}

but that is lengthy method and does deep search.

php


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Devsi Odedra
Solution 2 Justinas
Solution 3 Frankich