0

I have a multidimensional PHP array of the following form:

Array
(
    [0] => Array
        (
            [id] => 45
            [date] => 2013-05-16
        )

    [1] => Array
        (
            [id] => 30
            [date] => 2013-12-10
        )

    [2] => Array
        (
            [id] => 26
            [date] => 2014-03-27
        )

    [3] => Array
        (
            [id] => 34
            [date] => 2014-03-27
        )

)

I am trying to generate a list of the [id] values, separated by commas, using the following PHP code:

foreach ($my_array as $key => $value) { 
    if ($key == 0) {
        $id_list = $value[id];
    }
    if ($key !== 0 ) {
        $id_list .= "," . $value[id];
    }
}

I was hoping this would return

45,30,26,34

...but for some reason it returns

45,30,26,26

i.e. the penultimate ID is duplicated and the final ID is missed off. I have been staring at this for a while now but I can't see where I'm going wrong. Have I missed something obvious?

1
  • Would using implode work for your needs? Commented Sep 12, 2014 at 16:28

1 Answer 1

5

The better solution would be to not use those if() at all:

$ids = array();
foreach($arr as $val) {
   $ids[] = $val['id'];
}

$id_str = implode(',', $ids);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.