Foreach Usage In PHP, JavaScript, Java, C#, Python Programming Languages with Examples – POFTUT

Foreach Usage In PHP, JavaScript, Java, C#, Python Programming Languages with Examples

Loops are an important part of the programming languages. For and While loops are used for decades in different programming languages. Foreach provides similar functionality with a more elegant way by iterating over the given list. In this tutorial, we will examine foreach in different programming languages like PHP, JavaScript, Java, C# and Python.

PHP Foreach

PHP provides foreach in order to iterate over given arrays. There is two main usage syntax about PHP foreach.

Value Syntax

In value syntax, we will provide just the array which is named ARRAY_EXPRESSION and the VALUE. We will write operations to the STATEMENT

In this example, we will print array values to the standard output.

Key, Value Syntax

In Key and Value syntax will also get the key from the array and use it in the foreach.

In this example, we will print key and values into standard output

JavaScript Foreach

JavaScript is a very extensible language where most of the features are provided by objects. foreach is also provided by the object which is an array. It has the following syntax.

LEARN MORE  How To Sort List In Python Programming Language?


In this example, we will iterate over array named arr and print to the console.

Java Foreach

Java programming language actually does not provides native foreach keyword. But we can use other elements of Java like List, ArrayList and for.

For Syntax

We will use List and for to create foreach mechanism. TYPE is VALUE type and we will provide LIST.

We will iterate over string list and we will print to the standard output.

Foreach Syntax

After Java 8 List type provide forEach() function. So we can create a LIST and then iterate over elements with forEach() function. We will also use a lambda expression.

C# Foreach

C # provides the foreach statement in a native way.  We will provide the LIST with the in keyword and set ELEMENT with the given TYPE.

In this example, we will iterate over an integer list named lst.

Python Foreach

Python programming language does not provide the foreach keyword but the actual implementation of the for inPython is same as the foreach. We can iterate over List, Array, Dictionary type in python with for like below.

In this example, we will iterate over list named lst.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)