DEV Community

Amulya
Amulya

Posted on

PHP for Loop with code examples

PHP for loop is more like C or JavaScript if you already know these programming languages then PHP for loop must feel familiar to you. I am quickly going to show PHP for loop example code with PHP array data. But first let's understand how the PHP for loop looks and works. However, in practice; people use PHP foreach loop and PHP while while more often than the PHP for loop. Nevertheless, let's have a look at it.

PHP for loop stucture

/* example 1 */

for ($i = 1; $i <= 10; $i++) {
echo $i;
}

/* example 2 */

for (expr1; expr2; expr3):
statement
...
endfor;

PHP for Loop with Array Data Example

Here is a PHP multidimensional array and below this array there is a PHP for loop that is looping through the array and printing fruit names and fruit price that you can see in the image below this for loop. Or you can simply copy this code block and run it on your system or on online PHP compiler.

`$fruits = array(
array('name' => 'Apple', 'price' => 5.0),
array('name' => 'Orange', 'price' => 4.0),
array('name' => 'Guava', 'price' => 3.50),
array('name' => 'Banana', 'price' => 2.50),
array('name' => 'Grapes', 'price' => 3.0)
);

for($i = 0; $i < count($fruits); ++$i) {
echo 'Fruit Name: '. $fruits[$i]['name'] . ", Price $ " . $fruits[$i]['price'] . ' | ';
}`

Image description

PHP foreach loop structure

To loop over php array

foreach (iterable_expression as $value)
statement

To loop over php key-value pair array

foreach (iterable_expression as $key => $value)
statement

Top comments (1)

Collapse
 
dennistobar profile image
Dennis Tobar

Hello!

If you'd like, you can add syntax highlighting (colors that make code easier to read) to your code block like the following example.

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

This should make it a bit easier to understand your code. 😎

You could show how is the example with the same array, not only in for loop for fruits :)