You can either add multiple properties by adding multiple elements within a sub-array
$foodArray = [['name' => 'Apple', 'color' => 'Yellow'],
['name' => 'Banana', 'color' => 'yellow']];
foreach($foodArray as $fruit) {
echo $fruit['name']." - ".$fruit['color']." <br />";
}
Or if you just need these two properties, you can use the key as the name, and the value as the color.
$foodArray = ['Apple' => 'green', 'Banana' => 'yellow'];
foreach($foodArray as $fruit => $color) {
echo $fruit." - ".$color ." <br />";
}
- Live demo at https://3v4l.org/jGePl
Loop Through An Array In PHP with 2 or more properties - Stack Overflow
How do you look through a 2D array in PHP using a while loop
Loop through array while vs foreach [Noob Question]
bindParam (loop through array?)
What is a foreach loop in PHP?
How do you change array values inside a foreach?
Does foreach work with nested arrays?
You can either add multiple properties by adding multiple elements within a sub-array
$foodArray = [['name' => 'Apple', 'color' => 'Yellow'],
['name' => 'Banana', 'color' => 'yellow']];
foreach($foodArray as $fruit) {
echo $fruit['name']." - ".$fruit['color']." <br />";
}
Or if you just need these two properties, you can use the key as the name, and the value as the color.
$foodArray = ['Apple' => 'green', 'Banana' => 'yellow'];
foreach($foodArray as $fruit => $color) {
echo $fruit." - ".$color ." <br />";
}
- Live demo at https://3v4l.org/jGePl
For looping over multiple properties, you need to use multi-dimensional arrays.
Basic concept is that an array should contain arrays.
Now these arrays can have multiple properties.
You need to take key value pairs.
So, your array would be:
$foodArray = ['green' => 'apple', 'yellow' => 'banana'];
foreach ($foodArray as $foodColor => $food) {
echo $foodColor . ' = ' $food ."<br />";
}
Or else, you can define multi-dimensional array and loop over it:
$foodArray = [];
$foodArray['apple']['name'] = ['apple'];
$foodArray['apple']['color'] = ['green'];
$foodArray['banana']['name'] = ['banana'];
$foodArray['banana']['color'] = ['yellow'];
And loop over it.
foreach ($foodArray as $food) {
echo $food['color'] . ' = ' $food['name'] ."<br />";
}
You can multiple properties for each food item as it is a multi-dimensional array.