循环关联数组键[重复]

This question already has an answer here:

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'];'
</div>

You should use double quote mark

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

This is one way to do it

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

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