1

I need to change this array:

$array = [
        [0] => [
            'id' => '100'
        ],
        [1] => [
            'id' => '200'
        ],
        [2] => [
            'id' => '300'
        ]
    ];

Into this: $array2 = [100, 200, 300];

A long time ago I found a built-in PHP function which could do this for me. But i can't for the life of me remember which one it was. Of course I could do it manually, but it would be easier and more readable if I could use a builtin PHP function

Benjamin Tamasi
  • 662
  • 7
  • 18

2 Answers2

1

Use array_column like this: array_column($array, 'id');

Caleb
  • 2,197
  • 3
  • 19
  • 31
Benjamin Tamasi
  • 662
  • 7
  • 18
0

1st solution:

Use array_map() function with inline function:

$array2 = array_map(function($arrayElement){return $arrayElement['id'];}, $array);

2nd solution:

Use foreach loop:

function getValues($array, $index)
{
    $result = array();
    foreach($array as $element)
    {
        if(isset($element[$index])) //check if index exists
            $result[] = $element[$index];
    }

    return $result;
}

$array2 = getValues($array, 'id');

This function has two parameters: array from which you gets values and index, for example 'id'.

Result of two methods is the same:

Array
(
    [0] => 100
    [1] => 200
    [2] => 300
)
aslawin
  • 1,981
  • 16
  • 22