Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop Through An Array In PHP with 2 or more properties

Tags:

arrays

php

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?

like image 407
Hristian Yordanov Avatar asked Mar 28 '19 08:03

Hristian Yordanov


People also ask

How to loop through an array in PHP?

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.

What is a foreach loop in PHP?

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.

What are the different types of loops in PHP?

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.

Why is my array looping through multiple arrays at once?

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.


1 Answers

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
like image 119
Qirel Avatar answered Oct 09 '22 19:10

Qirel