>백엔드 개발 >PHP 튜토리얼 >PHP의 Foreach 루프

PHP의 Foreach 루프

PHPz
PHPz원래의
2024-08-29 12:41:54959검색

Foreach loop/loops are one of the best ways of providing an easy doorway in order to iterate over the array/arrays listed in the program. It only works when objects and arrays are present. Foreach loop/construct will issue error/errors when one uses it with variables and different data types/ uninitialized variables/variables. There are two kinds of expressing foreach loop in PHP. Check out below for the different types of syntax usage for the foreach loop in PHP. Foreach loop will work only on PHP7, PHP5, PHP4 versions.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

foreach(array as $value)
Statement/statements
foreach(array as $key => $value)
Statement/statements

The first form loop in the above syntax value of the current element in the loop will be assigned to the $value variable and also the internal pointer is advanced ahead by one. The second form loop in the above syntax is going to assign the current value to the current key i.e., current elements key is assigned to the $key variable and respect to that current value will be assigned to $value variable on each and every iteration.

Flowchart

The following is the representation of the foreach loop using a flowchart in PHP:

PHP의 Foreach 루프

How does Foreach Loop work in PHP?

Foreach works by looping through the values of the arrays. Each and every element/item in the array will be stored in $value/any other variable as needed. Foreach also called using the key and value elements as needed. In foreach, the array’s pointer is advanced by the one so that it will go to the next element in the array/arrays.

Examples to Implement Foreach Loop in PHP

Below are some of the examples to implement foreach loop in PHP:

Example #1

This is the first example of foreach to print the list of elements/items which are present in the array itself in the program using foreach function. Array1 which has array elements will be assigned to the value1 variable so that value1 variables current value will become the current element of the array1 by multiplying with the number “2”.

Code:

<?php
$array1 = array(1, 2, 3, 4, 6, 22, 32, 12, 11, 14, 16, 17, 18, 19, 28);
foreach ($array1 as $value1) {
$value1 = $value1 * 2;
echo $value1.", ";
}
?>

Output:

PHP의 Foreach 루프

Example #2

This is the program to print the array1 elements by passing the array1 values to the value1 at once using iterations of foreach. In the first foreach current elements are multiplied with 2 but didn’t give any output. After the loop again the new foreach loop stated bypassing the key values to $key1 and values to $value1 and every element we give to key1, value1 variable by using the iteration process of foreach. Then the output will show the array’s index values and the actual value stored in the particular index of an array.

Code:

<?php
$array1 = array(11, 14, 16, 17);
foreach ($array1 as $value1) {
$value1 = $value1 * 2;
}
foreach ($array1 as $key1 => $value1) {
echo "{$key1} => {$value1} - ";
print_r($array1);
}
?>

Output:

PHP의 Foreach 루프

Example #3

This is the program to print the actual array elements and also the array elements which are multiples of 2 of its only values. Here the array is directly passed inside of the foreach() function and then array values directly passing to the value1 variable through iteration of foreach.

Code:

<?php
echo "Actual Array List Items :\n";
foreach (array(1, 2, 3, 4, 5, 6,7) as $value1) {
echo $value1.", ";
}
echo "\nModified Array List numbers/Items: \n";
foreach (array(1, 2, 3, 4, 5, 6,7) as $value1) {
$value2 = $value1 * 2;
echo $value2.", ";
}
?>

Output:

PHP의 Foreach 루프

Example #4

This is the small examples of a foreach loop of PHP. Here we can see different types of foreach loops to illustrate the array’s elements with different types of declarations. The first foreach is declared by listing the array elements/values to the v1 variable by passing from the a1 variable through iteration of foreach. The second foreach will print the elements/values of the array with the array index values. The third foreach in the program is made just like the key and value format just like above. Fourth each in the program is to illustrate multi-dimensional arrays using the foreach function of PHP. The fifth foreach in the program is to print the dynamic array values. All those programs output shown in the output image below in detail.

Code:

<?php
/* foreach example with the value/values only */
$a1 = array(1, 2, 3, 17);
foreach ($a1 as $v1) {
echo "Current value of \$a1: $v1\n";
}
/* Small example of value (with the manual access notation which is printed for the illustration) */
$a1 = array(1, 2, 3, 17);
$i1 = 0;
foreach ($a1 as $v1) {
echo "\$a1[$i1] => $v1 \n";
$i1++;
}
/* key and value listing foreach example*/
$a1 = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a1 as $k1 => $v1) {
echo "\$a1[$k1] => $v1 \n";
}
/* multi-dimensional arrays example with foreach function*/
$a1 = array();
$a1[0][0] = "a";
$a1[0][1] = "b";
$a1[1][0] = "y";
$a1[1][1] = "z";
foreach ($a1 as $v2) {
foreach ($v2 as $v3) {
echo "$v3, ";
}
}
echo "\n";
/* Small example of dynamic arrays with foreach function*/
foreach (array(1, 2, 3, 4, 5) as $v1) {
echo "$v1, ";
}
?>

Output:

PHP의 Foreach 루프

Example #5

This is the program to check the number 3 in the list if the number 3 is found then it will print some text as mentioned below and then the loop will be broken.

Code:

<?php
$array2 = array( 'one', 'three', 'two', 'four', 'five' );
foreach( $array2 as $value2 ){
if( $value2 == 'three' ){
echo "Number three found in the second item of array!";
break;
}
}
?>

Output:

PHP의 Foreach 루프

Example #6

This is the example of foreach to capitalize on the chars/strings which are listed in the array and then print them using the foreach loop iteration method.

Code:

<?php
$a = array('pavansake','ben','tony');
foreach ($a as $k=>&$n)
$n = strtoupper($n);
echo "List of the items in the array by modifying into capital letters:: \n";
foreach ($a as $k=>$n)
echo "$n\n";
echo "\n";
echo "Array List with Index values:: \n";
print_r($a);
?>

Output:

PHP의 Foreach 루프

위 내용은 PHP의 Foreach 루프의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP의 While 루프다음 기사:PHP의 While 루프