PHP array_filter to get only one value from an array

The filter function needs to return a boolean(or any value that can be coerced to true) for each item so that it can be spared. So in your case it is always returning true for every element in the array

To get the result you 'd have to array_walk;

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


 array_walk($data, function($value, $key) use ($data){
                  $data[$key] = $value[0];
           })

Try this code

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

    $ids = array_column($data, 0);
    var_dump($ids);

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.

Tags:

Php

Arrays