What is php foreach

PHP foreach() loop for indexed and associative arrays

In this tutorial, we look at the PHP foreach() loop. We also look at how to use it while working with an indexed or associative array. This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.

Table of Contents — PHP foreach:

What is foreach in PHP?

The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.

Syntax of PHP foreach():

The foreach() method has two syntaxes, one for each type of array.

The syntax for indexed arrays is as given in the following code block:

foreach (iterable as $value) statement 

The syntax for associative arrays:

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

Here, “Iterable” is the required parameter. It is the array or the variable containing the array. “$value” is a variable that stores the current element in each iteration.

Читайте также:  Генератор css меню i

Associated array, uses keys and values, and hence the $key & $values in the second syntax represent the same accordingly.

Code & Explanation:

In this section, we first look at how the foreach() function works on an indexed array followed by which we look at it’s working on an associative array.

PHP Foreach() on Indexed arrays:

 $flexiple = array("Hire", "top", "freelance", "developers"); foreach ($flexiple as $value)  echo "$value 
"
; > ?>

The output of the above code snippet would be:

Hire Top Freelance developers 

PHP Foreach() on an Associative array:

 $freelancer = array( "name" => "Eric", "email" => "Eric@gmail.com", "age" => 22, "gender" => "male" ); // Loop through employee array foreach($freelancer as $key => $value)  echo $key . ": " . $value . "
"
; > ?>

The output of the above code snippet would be:

name: Eric email: Eric@gmail.com age: 22 gender: male 

Now let’s look at a case where we pass a second argument. As you can see the key and the values of the associative array were printed. Additionally, we replaced “=>” with a “:” to make it more readable.

Closing thoughts:

The foreach() method would return an error in case you use it on variables with a different data type. Additionally, the foreach() method does not modify the values of the internal pointer.

Once you have understood the working to the foreach() method try working with the for loop.

Источник

foreach

Конструкция foreach предоставляет простой способ перебора массивов. Foreach работает только с массивами и объектами, и будет генерировать ошибку при попытке использования с переменными других типов или неинициализированными переменными. Существует два вида синтаксиса:

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

Первый цикл перебирает массив, задаваемый с помощью array_expression. На каждой итерации значение текущего элемента присваивается переменной $value и внутренний указатель массива увеличивается на единицу (таким образом, на следующей итерации цикла работа будет происходить со следующим элементом).

Второй цикл будет дополнительно соотносить ключ текущего элемента с переменной $key на каждой итерации.

Замечание:

Когда оператор foreach начинает исполнение, внутренний указатель массива автоматически устанавливается на первый его элемент Это означает, что нет необходимости вызывать функцию reset() перед использованием цикла foreach.

Так как оператор foreach опирается на внутренний указатель массива, его изменение внутри цикла может привести к непредсказуемому поведению.

Для того, чтобы напрямую изменять элементы массива внутри цикла, переменной $value должен предшествовать знак &. В этом случае значение будет присвоено по ссылке.

$arr = array( 1 , 2 , 3 , 4 );
foreach ( $arr as & $value ) $value = $value * 2 ;
>
// массив $arr сейчас таков: array(2, 4, 6, 8)
unset( $value ); // разорвать ссылку на последний элемент
?>

Указатель на $value возможен, только если на перебираемый массив можно ссылаться (т.е. если он является переменной). Следующий код не будет работать:

Ссылка $value на последний элемент массива остается даже после того, как оператор foreach завершил работу. Рекомендуется уничтожить ее с помощью функции unset() .

Замечание:

Оператор foreach не поддерживает возможность подавления сообщений об ошибках с помощью префикса ‘@’.

Вы могли заметить, что следующие конструкции функционально идентичны:

$arr = array( «one» , «two» , «three» );
reset ( $arr );
while (list(, $value ) = each ( $arr )) echo «Значение: $value
\n» ;
>

foreach ( $arr as $value ) echo «Значение: $value
\n» ;
>
?>

Следующие конструкции также функционально идентичны:

$arr = array( «one» , «two» , «three» );
reset ( $arr );
while (list( $key , $value ) = each ( $arr )) echo «Ключ: $key ; Значение: $value
\n» ;
>

foreach ( $arr as $key => $value ) echo «Ключ: $key ; Значение: $value
\n» ;
>
?>

Вот еще несколько примеров, демонстрирующие использование оператора:

foreach ( $a as $v ) echo «Текущее значение переменной \$a: $v .\n» ;
>

/* Пример 2: значение (для иллюстрации массив выводится в виде значения с ключом) */

$i = 0 ; /* только для пояснения */

foreach ( $a as $v ) echo «\$a[ $i ] => $v .\n» ;
$i ++;
>

$a = array(
«one» => 1 ,
«two» => 2 ,
«three» => 3 ,
«seventeen» => 17
);

foreach ( $a as $k => $v ) echo «\$a[ $k ] => $v .\n» ;
>

/* Пример 4: многомерные массивы */
$a = array();
$a [ 0 ][ 0 ] = «a» ;
$a [ 0 ][ 1 ] = «b» ;
$a [ 1 ][ 0 ] = «y» ;
$a [ 1 ][ 1 ] = «z» ;

foreach ( $a as $v1 ) foreach ( $v1 as $v2 ) echo » $v2 \n» ;
>
>

/* Пример 5: динамические массивы */

foreach (array( 1 , 2 , 3 , 4 , 5 ) as $v ) echo » $v \n» ;
>
?>

Распаковка вложенных массивов с помощью list()

В PHP 5.5 была добавлена возможность обхода массива массивов с распаковкой вложенного массива в переменные цикла, передав list() в качестве значения.

foreach ( $array as list( $a , $b )) // $a содержит первый элемент вложенного массива,
// а $b содержит второй элемент.
echo «A: $a ; B: $b \n» ;
>
?>

Результат выполнения данного примера:

Можно передавать меньшее количество элементов в list() , чем находится во вложенном массиве, в этом случае оставшиеся значения массива будут проигнорированы:

foreach ( $array as list( $a )) // Обратите внимание на отсутствие $b.
echo » $a \n» ;
>
?>

Результат выполнения данного примера:

Если массив содержит недостаточно элементов для заполнения всех переменных из list() , то будет сгенерировано замечание об ошибке:

foreach ( $array as list( $a , $b , $c )) echo «A: $a ; B: $b ; C: $c \n» ;
>
?>

Результат выполнения данного примера:

Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:

Источник

What is php foreach

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

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

The first form traverses the iterable given by iterable_expression . On each iteration, the value of the current element is assigned to $value .

The second form will additionally assign the current element’s key to the $key variable on each iteration.

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key() .

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

$arr = array( 1 , 2 , 3 , 4 );
foreach ( $arr as & $value ) $value = $value * 2 ;
>
// $arr is now array(2, 4, 6, 8)
unset( $value ); // break the reference with the last element
?>

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset() . Otherwise you will experience the following behavior:

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach ( $arr as $key => $value ) // $arr[3] will be updated with each value from $arr.
echo » < $key >=> < $value >» ;
print_r ( $arr );
>
// . until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

It is possible to iterate a constant array’s value by reference:

Note:

foreach does not support the ability to suppress error messages using @ .

Some more examples to demonstrate usage:

/* foreach example 1: value only */

foreach ( $a as $v ) echo «Current value of \$a: $v .\n» ;
>

/* foreach example 2: value (with its manual access notation printed for illustration) */

$i = 0 ; /* for illustrative purposes only */

foreach ( $a as $v ) echo «\$a[ $i ] => $v .\n» ;
$i ++;
>

/* foreach example 3: key and value */

$a = array(
«one» => 1 ,
«two» => 2 ,
«three» => 3 ,
«seventeen» => 17
);

foreach ( $a as $k => $v ) echo «\$a[ $k ] => $v .\n» ;
>

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a [ 0 ][ 0 ] = «a» ;
$a [ 0 ][ 1 ] = «b» ;
$a [ 1 ][ 0 ] = «y» ;
$a [ 1 ][ 1 ] = «z» ;

foreach ( $a as $v1 ) foreach ( $v1 as $v2 ) echo » $v2 \n» ;
>
>

/* foreach example 5: dynamic arrays */

foreach (array( 1 , 2 , 3 , 4 , 5 ) as $v ) echo » $v \n» ;
>
?>

Unpacking nested arrays with list()

It is possible to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

foreach ( $array as list( $a , $b )) // $a contains the first element of the nested array,
// and $b contains the second element.
echo «A: $a ; B: $b \n» ;
>
?>

The above example will output:

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

foreach ( $array as list( $a )) // Note that there is no $b here.
echo » $a \n» ;
>
?>

The above example will output:

A notice will be generated if there aren’t enough array elements to fill the list() :

foreach ( $array as list( $a , $b , $c )) echo «A: $a ; B: $b ; C: $c \n» ;
>
?>

The above example will output:

Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:

Источник

PHP foreach Loop

The foreach loop — Loops through a block of code for each element in an array.

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Examples

The following example will output the values of the given array ($colors):

Example

foreach ($colors as $value) echo «$value
«;
>
?>

The following example will output both the keys and the values of the given array ($age):

Example

You will learn more about arrays in the PHP Arrays chapter.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP foreach Keyword

The foreach keyword is used to create foreach loops, which loops through a block of code for each element in an array.

Read more about foreach loops in our PHP foreach Loop Tutorial.

More Examples

Example

Print keys and values from an associative array:

foreach($people as $person => $age) echo «$person is $age years old»;
echo «
«;
>
?>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью