PHP Array foreach - Tutorial Kart

PHP Array foreach

PHP Array foreach

PHP Array foreach is a construct in PHP that allows to iterate over arrays easily.

In this tutorial, we will learn the syntax of foreach loop construct and go through following scenarios

1. foreach loop to iterate over PHP array of numbers. 2. foreach loop to iterate over key-value pairs of PHP array. 3. foreach loop to iterate over only values of PHP array with key-value pairs. 4. nested foreach loop to iterate over multidimensional PHP array.

Syntax ? foreach

The syntax of foreach() with array is

foreach (array_expression as $value) { statement(s)

}

Using this syntax, you can iterate over arrays containing just the values as elements, or iterate only over values of an array with key-value pairs.

If you would like to access both key and value of key-value pairs in array with foreach, use the following syntax

foreach (array_expression as $key => $value) { statement(s)

}

Now, you can access both key and value using variable $key and $value variables respectively.

Example ? foreach on Array of Integers

In the following program, we take an array of integers and iterate over the elements using foreach loop.

PHP Program

Program Output

Example ? Array foreach ? Iterate over Array key-value pairs

In the following program, we take an array of integers and iterate over the elements using foreach loop.

PHP Program

Program Output

PHP Array foreach ? Iterate over elements of Array

Example ? Array foreach ? Iterate over values of Array with Key-Value pairs

In the following program, we take an array of key-value pairs and iterate over only values using foreach loop.

PHP Program

Program Output

Example ? Nested foreach ? Iterate over values of Multidimensional Array

In the following program, we take a two dimensional array and iterate over the elements using foreach loop.

PHP Program

Program Output

Conclusion

In this PHP Tutorial, we learned the syntax of foreach in PHP, and how to use foreach to iterate over the elements of an array.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download