Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_filter to get only one value from an array

Tags:

arrays

php

I'm trying to exclude foreach-loops and refactor them with array functions. I was under the assumption the code below would give me a result with all first items from the source array.

<?php
    $data= [
        0 => [1, 'test1'],
        1 => [2, 'test2'],
        2 => [3, 'test3'],
    ];

    $ids = array_filter($data, function($item) {
        return $item[0];
    });

    var_dump($ids);

But when I var_dump $ids I get the output:

array (size=3)
  0 => 
    array (size=2)
      0 => int 1
      1 => string 'test1' (length=5)
  1 => 
    array (size=2)
      0 => int 2
      1 => string 'test2' (length=5)
  2 => 
    array (size=2)
      0 => int 3
      1 => string 'test3' (length=5)

Why isn't the output:

array (size=3)
  0 => int 1
  1 => int 2
  2 => int 3
like image 262
Ben Fransen Avatar asked May 18 '16 12:05

Ben Fransen


1 Answers

array_filter is used for filtering out elements of an array based on whether they satisfy a certain criterion. So you create a function that returns true or false, and test each element of the array against it. Your function will always return true, since every array has a first element in it, so the array is unchanged.

What you're looking for is array_map, which operates on each element in an array by running the callback over it.

<?php
$data= [
    0 => [1, 'test1'],
    1 => [2, 'test2'],
    2 => [3, 'test3'],
];

$ids = array_map(function($item) {
    return $item[0];
}, $data);

var_dump($ids);

As another answer mentions, if all you want to do is extract a single "column", then array_column is a much simpler option.

like image 117
iainn Avatar answered Nov 07 '22 04:11

iainn