KeepCool KeepCool - 1 month ago 10
PHP Question

Search multi-dimesional array and return specific value

Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things.

Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:

$data = '13,4,3|65,1,1|27,3,2';

$return_2d_array = array_map (
function ($_) {return explode (',', $_);},
explode ('|', $data)
);


I'm able to return any value using

echo $return_2d_array[1][0];


But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).

Answer

Run one more foreach loop like this:

$value_to_search = 27;
foreach($return_2d_array as $array){ 
    if($array[0] == $value_to_search){ 
        echo $array[1];  // will give 3
        break; 
    } 
}

Here's the live demo.