0

Assuming I have an array like

$arr = array (
    array( 'foo' => 'Lorem' ),
    array( 'foo' => 'ipsum' ),
    array( 'foo' => 'dolor' ),
    array( 'foo' => 'sit'   )
);

How can I quickly convert this array into an indexed array for the key "foo"? So that the result is

Array
(
    [0] => 'Lorem'
    [1] => 'ipsum'
    [2] => 'dolor'
    [3] => 'sit'
)

Are there any quick ways with PHP functions? Or do I simply have to create a new array, iterate over the other one and insert the values manually.

fritzmg
  • 2,494
  • 3
  • 21
  • 51
  • @RahilWazir: it's not a duplicate. The solution to that other question is using `array_values`, however `array_values` will simply result in the same array in my case. See Answers below. – fritzmg Feb 23 '14 at 12:11

3 Answers3

2

You could make use of array_column which is available from PHP 5.5

print_r(array_column($arr,'foo'));

The code...

<?php
$arr = array (
    array( 'foo' => 'Lorem' ),
    array( 'foo' => 'ipsum' ),
    array( 'foo' => 'dolor' ),
    array( 'foo' => 'sit'   )
);

print_r(array_column($arr,'foo'));

Demo

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • 1
    Oh I see, too bad this wasn't introduced earlier :). So I guess I have to do it manually when PHP 5.5 is not available. – fritzmg Feb 09 '14 at 09:44
  • @Spooky: Or, you could say `if (!function_exists('array_column')) { function array_column($arr, $colname, $keyname=null) { /* do exactly what array_column does */ } }`, and once you switch to 5.5, you'll start using the built-in version automatically... :) – cHao Feb 09 '14 at 09:53
  • @cHao, That was perfect! – Shankar Narayana Damodaran Feb 09 '14 at 09:56
2

You can use array_map(). This works -

$new_arr = array_map(function($v){return $v['foo'];}, $arr);
var_dump($new_arr);
//  OUTPUT
array
  0 => string 'Lorem' (length=5)
  1 => string 'ipsum' (length=5)
  2 => string 'dolor' (length=5)
  3 => string 'sit' (length=3)
Kamehameha
  • 5,423
  • 1
  • 23
  • 28
1

.. Or using array_map(..):

<?php
$arr = array (
    array( 'foo' => 'Lorem' ),
    array( 'foo' => 'ipsum' ),
    array( 'foo' => 'dolor' ),
    array( 'foo' => 'sit'   )
);

print_r(array_map(function($x){return $x["foo"];}, $arr));

Output:

Array
(
    [0] => Lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
)
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104