Different types of loops can be used in PHP. The foreach loop is one of them. This loop is used primarily lớn parse array và object variables. When the total number of iterations of the loop is not defined, it is better to use a foreach loop than another loop. The number of iterations of this loop will depend on the number of array elements or the number of properties of the object used in the loop for reading values. How this loop can be used for reading array và object variables has been shown in this tutorial.
Bạn đang xem: Php
Syntax:
The foreach loop can be used to read the array values only or read both keys and values of the array.
The following foreach loop is used for reading the element values of an array. It can be used to lớn read both numeric & associative arrays. Each element value of the array will be stored in a variable in each iteration.
The following foreach loop is used for reading the element values of an array. It is mainly used to lớn read associative arrays. In each iteration of the loop, each key và value of the array will be stored in two variables.
Xem thêm: Xem Tử Vi Hàng Ngày 12 Cung Hoàng Đạo Song Tử Hôm Nay, Tử Vi Ngày Mai
Example-1: Reading a numeric array
The following example shows how to lớn read the numeric array using the foreach loop. Create a PHP file with the following script. A numeric array named $num_array of 10 elements has been declared in the script, & an empty array named $new_array has been declared to lớn store the even numbers from the numeric array. The foreach loop has been used lớn iterate the numeric array, và the ‘if’ statement has been used to lớn find out the even numbers from the $num_array and stored all even numbers into the $new_array. Another foreach loop has been used to lớn print the values of $num_array.
//Declare a numeric array$num_array = array(12, 90, 15, 6, 32, 38, 75, 57, 60, 78);//Declare an empty array$new_array = array();//initialize the index for the empty array$index = 0; echo "The array values are : "; /* Iterate the numeric array to lớn find out the numbers divisible by 5and store in a new array */foreach ($num_array as $value) if ($value%5 == 0) $new_array<$index> = $value; $index++; echo $value." "; echo "The list of numbers which are divisible by 5 : "; //Print the values of the $new_array arrayforeach ($new_array as $value) echo $value." ";?>
Output:
The following output đầu ra will appear after running the script from the server. The đầu ra shows that there are four even numbers in the numeric array.

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. Are published: Tutorials4u Help.