1

I have the following array

Array
(
    [0] => Array
        (
            [id] => 1120
        )

    [1] => Array
        (
            [id] => 1127
        )

    [2] => Array
        (
            [id] => 16101
        )

    [3] => Array
        (
            [id] => 16441
        )

    [4] => Array
        (
            [id] => 18447
        )
)

i want to convert the above array into this form:

Array
    (
        [0]  => 1120

        [1] =>  1127

        [2] => 16101

        [3] => 16441

        [4] => 18447
    )

but condition is this must be done without using foreach. Is this possible?

halfer
  • 19,824
  • 17
  • 99
  • 186
Amrinder Singh
  • 5,300
  • 12
  • 46
  • 88

6 Answers6

4

Solution for PHP >= 5.5 - array_column function:

// assuming $arr is your initial array
$result = array_column($arr, 'id');

var_dump($result);
// the output:
Array
    (
        [0]  => 1120

        [1] =>  1127

        [2] => 16101

        [3] => 16441

        [4] => 18447
    )

http://php.net/manual/en/function.array-column.php

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

You can do it using array_column function

$final_array = array_column($your_array, "id");
Hardik Solanki
  • 3,153
  • 1
  • 17
  • 28
0

You can use array_column to do this.

var_dump(array_column([['id' => 1],['id'=>2]], 'id'));

/*
gives you..

array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
*/
Sherif
  • 11,786
  • 3
  • 32
  • 57
0
array_combine(array_keys($arr), array_map(function($item) { return $item['id']; }, $arr));
Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
0

For PHP versions >=4.0.6 you can simply use array_map like as

$arr = array(array('id' => 1),array('id' => 2),array('id' => 3));
function call_function($v){ 
    return $v['id'];
}
$result = array_map('call_function',$arr);
print_r($result);

Instead you can simply use reset function as @Ghost said like as

$arr = array(array('id' => 1),array('id' => 2),array('id' => 3));
$result = array_map('reset',$arr);
print_r($result);

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

Demo

Community
  • 1
  • 1
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0
$arrFirstArray = array(
    '0' => array(
        'id' => 1120
    ),
    '1' => array(
        'id' => 1127
    ),
    '2' => array(
        'id' => 16101
    ),
    '3' => array(
        'id' => 16441
    ),
    '4' => array(
        'id' => 18447
        ));

echo $intFirstArray = count($arrFirstArray);

$arrSecondArray = array();
for ($intI = 0; $intI < $intFirstArray; $intI++)
{
    global $arrSecondArray;
    $arrSecondArray[] = $arrFirstArray[$intI]['id'];
}
echo '<pre>';
print_r($arrSecondArray);

This will definitely work.

Hiren Rathod
  • 946
  • 1
  • 7
  • 21