Php array_filter to get only one value from an array

I am trying to exclude foreach-loops and reorganize them using array functions. I was under the assumption that the code below will give me the result with all the first elements from the original 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 not a conclusion:

array (size=3)
  0 => int 1
  1 => int 2
  2 => int 3
+4
source share
5 answers

array_filterused to filter array elements based on whether they satisfy a specific criterion. Thus, 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 each array has the first element in it, so the array does not change.

, , array_map, , .

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

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

var_dump($ids);
+7

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

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

    var_dump($ids);
+1

( , true) , . true

, array_walk;

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


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

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

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

, array_filter, true, false. 0 FALSE. .

, id 2, 2

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

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

var_dump($ids);

array(1) {
  [1] =>
  array(2) {
    [0] =>
    int(2)
    [1] =>
    string(5) "test2"
  }
}
0

All Articles