Search code examples
phparraysarray-filter

Get an array column based on the values of another column in PHP


I have a multi-column PHP array as

Array (
    Array ('col1', 'col2', 'col3'),
);

How can I get an array of col2 if col1 is greater than a specific value?

I can do it by a foreach loop, but I think it should be possible with a native function like array_filter.


Solution

  • Simply put, you're better with a foreach loop, as you're not going to have to make multiple iterations of the array. You want to both filter and modify the array, which requires using both array_filter() and array_map() in order to get what you want:

    <?php
    
    $arr = [
        [5, 'col2-1', 'col3'],
        [10, 'col2-2', 'col3']
    ];
    
    $res = array_filter($arr, function($item) {
        return $item[0] > 7;
    });
    
    $res = array_map(function($item) {
        return $item[1];
    }, $res);
    
    var_dump($res);
    

    Test here: https://3v4l.org/HRTOJ