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.

1
  • @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. Commented Feb 23, 2014 at 12:11

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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, That was perfect!
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)

Comments

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
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.