3

This is a very basic quesion i know but im facing difficulties. I have an array like this:

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

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

)

or you can say:

array(12) {
[0]=> array(1) { ["id"]=> int(10772) } [1]=> array(1) { ["id"]=> int(10775) }

but i need only the value in a string format like:

"10772,10775" or array("10772", "10775") 

how can i achieve that.

1
  • You need to loop through your array to get what you need.
    – andrew
    Commented Feb 16, 2016 at 12:53

2 Answers 2

14

use array_column function:

$array = array(
    array(
        'id' => 123456
    ),
    array(
        'id' => 52458
    ),
);

$id_array = array_column($array, 'id');

print_r($id_array);

output:

Array
(
    [0] => 123456
    [1] => 52458
)

for PHP version < 5.5 you can use:

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

print_r($data);
4
  • 1
    this is only available in php 5.5+
    – andrew
    Commented Feb 16, 2016 at 12:54
  • 1
    @andrew but it's a good answer. OP doesn't said the version he needs, so the answer is the best and simplest way Commented Feb 16, 2016 at 12:56
  • edited for php version < 5.5 Commented Feb 16, 2016 at 12:58
  • thank you very much for fast answer yes im not worried about php version as im using 5.6 Commented Feb 16, 2016 at 13:13
1

You are looking for array_map function

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

Check this link for more info http://php.net/manual/en/function.array-map.php

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.