I'm trying to create an array with two properties and loop through it. But I don't know how to do it.
In this example a have one property:
$foodArray = ["apple", "banana"];
foreach ($foodArray as $food) {
echo $food ."<br />";
}
Now I want to add in the array - green to apple and yellow to banana and loop the same way. How to do it in the best way?
In this article, we will introduce methods to loop through an array in PHP. Using these methods, we will traverse through an array. We can use a foreach loop to loop through an array. We can also access array elements using this loop. The correct syntax to use this loop is as follows.
The foreach loop - Loops through a block of code for each element in an array. The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
There are 4 types of loops in PHP: while, do-while, for, and foreach. An array allows you to create a collection of related items. In this example we will initialize and array of colors. In this sample we define an array of colors and print out a random color.
Well the problem is of course your nested foreach loop. Because for each element of your $data1 array you loop through the entire $data2 array (So in total there are $data1 * $data2 iterations). To solve this you have to loop through both arrays at once.
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 />";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With