Inserting Multidimensional Array Elements in a Loop in PHP
Let's see how insertions are performed when iterating through multidimensional arrays. Suppose, for example, we have the following array:
<?php
$users = [
[
'name' => 'user1',
'age' => 30,
],
[
'name' => 'user2',
'age' => 31,
],
[
'name' => 'user3',
'age' => 32,
],
];
?>
Let's iterate through it with a loop and form strings from its elements:
<?php
foreach ($users as $user) {
echo $user['name'] . ': ' . $user['age'] . '<br>';
}
?>
Let's simplify our code by using variable interpolation:
<?php
foreach ($users as $user) {
echo "{$user['name']}: {$user['age']}<br>";
}
?>
Let's simplify even more by removing quotes from the keys:
<?php
foreach ($users as $user) {
echo "$user[name]: $user[age]<br>";
}
?>
Given the following array:
<?php
$products = [
[
'name' => 'product1',
'price' => 100,
'amount' => 5,
],
[
'name' => 'product2',
'price' => 200,
'amount' => 6,
],
[
'name' => 'product3',
'price' => 300,
'amount' => 7,
],
];
?>
Using this array, output a column of products in some format you come up with.