How to create an array of specific values from another multidimensional array

How to create an array of specific values from another multidimensional array

Let’s imagine that we have an array:

$arrays = [
    [
        'name' => 'John',
        'target_id' => 998
    ],
    [
        'name' => 'Kim',
        'target_id' => 1002
    ],
    [
        'name' => 'Bob',
        'target_id' => 256
    ],
];

And as a result, we are going to have this array:

$newArray = [998, 1002, 256];

The typical way is to create a loop, go through each array, and save the specific values.

Example:

$newArray = [];
foreach ($arrays as $itemArray) {
    if (isset($itemArray['target_id'])) {
        $newArray[] = $itemArray['target_id'];
    }
}

Output:

print_r($newArray);

/**
Array
(
    [0] => 998
    [1] => 1002
    [2] => 256
)
*/

But also, we have the simplest way to do it using native array_column() function.

Example:

$arrays = [
    [
        'name' => 'John',
        'target_id' => 998
    ],
    [
        'name' => 'Kim',
        'target_id' => 1002
    ],
    [
        'name' => 'Bob',
        'target_id' => 256
    ],
];

$newArray = array_column($arrays, 'target_id');

Output:

print_r($newArray);

/*
Array
(
    [0] => 998
    [1] => 1002
    [2] => 256
)
*/

Using:

array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array

If we want to create an indexed array by a specific key, we should pass an optional parameter index_key.

Example:

$arrays = [
    [
        'name' => 'John',
        'target_id' => 998
    ],
    [
        'name' => 'Kim',
        'target_id' => 1002
    ],
    [
        'name' => 'Bob',
        'target_id' => 256
    ],
];

$newArray = array_column($arrays, 'name','target_id');

Output:

print_r($newArray);

/*
Array
(
    [998] => 'John'
    [1002] => 'Kim'
    [256] => 'Bob'
)
*/

Leave a Reply

Your email address will not be published. Required fields are marked *