phparraysmultidimensional-arrayfilter

Get element value from a 2d array row which qualifies because of another column value


I have the following array:

Array ( 
    [0] => Array ( [Country] => Americas [Out_Count] => 14 ) 
    [1] => Array ( [Country] => Belgium [Out_Count] => 2 ) 
    [2] => Array ( [Country] => China [Out_Count] => 33 ) 
    [3] => Array ( [Country] => France [Out_Count] => 7 ) 
)

I have a variable as follows:

$los = 'Belgium';

What I'd like to do is search the array and bring back the value of Out_Count to a variable.

I can use the following:

$key = array_search($los, array_column($outs, 'Country'));

This brings back the Key, in this case 1 for Belgium but I need the Out_Count value and I'm utterly stumped on how to achieve this.


Solution

  • Nice choice of array_column()! Just extract an array with Country as the key and Out_Count as the value:

    $los = 'Belgium';
    $result = array_column($outs, 'Out_Count', 'Country')[$los];
    

    To do it your way:

    $los = 'Belgium';
    $key = array_search($los, array_column($outs, 'Country'));
    $result = $outs[$key]['Out_Count'];
    

    Or:

    $result = $outs[array_search($los, array_column($outs, 'Country'))]['Out_Count'];