0

I have one index array which contain associative array. Like this

$arr = array(
            array("id" => 1,"name" => "student1"),
            array("id" => 2,"name" => "student2"),
            array("id" => 3,"name" => "student3"),
        );

Now I want output like this

1,2,3 // output

I have solution for it but I am searching for better way to do that. Here it is

$ids = "";
for($i=0;$i<count($arr);$i++)
{
    $ids .= $arr[$i]['id'].",";
}

$ids = rtrim($ids,",");
echo $ids; // output : 1,2,3

Is there any better way to achieve it?

Thanks in advance

4 Answers4

3

If you have php version >= 5.5 then try,

echo implode(",",array_column($arr,'id'));
Nouphal.M
  • 6,304
  • 1
  • 17
  • 28
3

Alternative using array_map() if you don't have PHP 5.5+:

echo implode(',', array_map(function($v) { return $v['id']; }, $arr));

Demo

billyonecan
  • 20,090
  • 8
  • 42
  • 64
0

try this code

<?php

    $arr = array(
                array("id" => 1,"name" => "student1"),
                array("id" => 2,"name" => "student2"),
                array("id" => 3,"name" => "student3"),
            );
    $str = "";      
    foreach ($arr as $value)        
    {

        $str=$str.$value["id"].",";
    }
    $str = substr($str, 0, -1);
    echo $str;
    ?>
Janak Prajapati
  • 896
  • 1
  • 9
  • 36
0
foreach ($arr as $val){
$ids[]=$val['id'];
}
echo implode(($ids),',');
sinisake
  • 11,240
  • 2
  • 19
  • 27