Custom PHP function arrayCols()

Source: Jopa - MyTechSolutions.com
Published: 2021-02-05

PHP coding trick, ever wanted more than one column from an array? The php built in function array_columns() is nice, though when you want two or more colums from an array this little function will get them for you.

  function arrayCols(array $arr, $keys) {
    if (!is_array($keys)) $keys = [$keys];
    return array_map(function ($item) use ($keys) {
      $out = [];
      foreach($keys as $key){
        $out[$key] = isset($item[$key])?$item[$key]:false;
      }
      return $out;
    }, $arr);
  }

 


add comment