0

I have these data array stored in variable $ids

array(3) {
  [0]=>
  array(1) {
    ["id"]=>
    string(3) "472"
  }
  [1]=>
  array(1) {
    ["id"]=>
    string(3) "475"
  }
  [26]=>
  array(1) {
    ["id"]=>
    string(3) "498"
  }
}

How can I get value of each id? I tried with for loop but it's not working.

for ($i=0; $i < count($ids); $i++){
   echo "ID is " . $ids['id'][$i];
}
Abaij
  • 853
  • 2
  • 18
  • 34

3 Answers3

3

Try the foreach loop instead:

foreach($ids as $id)
{
   echo "ID is " . $id['id'];
}

Because your keys are are not like 1,2,3...., the for loop won't work, but foreach will.

mega6382
  • 9,211
  • 17
  • 48
  • 69
0

If you have a non-sequential array order you can use foreach instead of for loop.

Demo: https://3v4l.org/ViHoW

<?php

$datas = array(
    0 => array(
        'id' => '472'
    ),
    1 => array(
        'id' => 475
    ),
    26 => array(
        'id' => '498'
    )
);

foreach ($datas as $data) {
    echo $data['id'] . PHP_EOL;
}

or if you really want to use for loop do it like this.

Demo v2: https://3v4l.org/EYlft

<?php

$datas = array(
    0 => array(
        'id' => '472'
    ),
    1 => array(
        'id' => '475'
    ),
    26 => array(
        'id' => '498'
    )
);


$datas = array_values($datas); // array_values will re-index your array to 0, 1, 2, 3, ...
$data_count = count($datas); // make it a habit not to use function in for loop header to prevent multiple execution.

for ($i = 0; $i < $data_count; $i++) {
    echo $datas[$i]['id'] . PHP_EOL;
}
Mark
  • 780
  • 1
  • 6
  • 17
0

For demo purpose. This is how you can do it with a for loop and with the array still intact. (No array_values messing with the keys).

$ids = array(0=>
array( 
"id"=>"472"
),
1=>
array(
"id"=>"475"
),
26=>
array(
"id"=>"498"
));

$keys = array_keys($ids);

For($i=0; $i<count($keys); $i++){
    Echo $ids[$keys[$i]]["id"] ."\n";
}

I use array_keys to get the keys or $ids.
Then I for loop the keys and use the keys as key in $ids.
Yes it's messy...

https://3v4l.org/eUBAg

Andreas
  • 23,610
  • 6
  • 30
  • 62