0

I want to loop through an associate array.

foreach($details as $key=>$value){
echo  $details['image1'];
}

Above code works fine.

What i want if i can replace the 1 in $details['image1'] to 2,3,4 ..etc what i tried

$j=i;
foreach($details as $key=>$value){
echo  $details['image.$j'];
$j++;
}

But it does not work. It there a way to dynamically change the key of associate array. like

'$details['image2'];
$details['image3'];'
Waqas Kanju
  • 94
  • 12
  • because it takes $i as literal not as variable – Waqas Kanju Aug 09 '19 at 12:13
  • 2
    I don't know how you create `$details` array, but you probably want to make an array of images instead of this mess. `$details = ['images' => ['image1', 'image2', ...]];` – HTMHell Aug 09 '19 at 12:14
  • 2
    I'm not sure I understand the point of iterating over the keys of an array if the foreach body recreates different keys anyways. It almost looks like what you want to do is `foreach($details as $key=>$value) { echo $value; }`. Am I missing something? – SirDarius Aug 09 '19 at 12:17
  • The actual code is some thing like this `` I have to dynamicaly load database pictures and show it in slider. – Waqas Kanju Aug 09 '19 at 12:21

3 Answers3

0

You should use double quote mark

$j=i;
foreach($details as $key=>$value){
   echo  $details["image{$j}"];
   $j++;
}
Maksym Fedorov
  • 6,383
  • 2
  • 11
  • 31
0

This is one way to do it

$j = $i;
$newArray = [];
foreach ($details as $key => $value) {
    $newArray['image'. $j] = $value;
    $j++;
 }
failedCoder
  • 1,346
  • 1
  • 14
  • 38
0

In echo $details['image.$j']; $j is inserted as a literal.

You can either use

  1. echo $details['image'.$j]; or
  2. echo $details["image{$j}"];

to correctly concat.

Although you actually do not need a foreach loop using this syntax. A simple for-loop would be sufficient.

for ($i = 0; $i < count($details); $i++)
{
  echo  $details["image.{$i}"];
}

Using foreach you probably do not need to count up $i ... but that depends on your array.

Have a look at https://www.php.net/manual/en/control-structures.foreach.php

AnUser1
  • 79
  • 8