For each key value php

Используем foreach для прохода по всему массиву PHP

Часто нужно пройти по всем элементам массива PHP и провести какую-нибудь операцию над каждым элементом. Например, вы можете вывести каждое значение в таблицу HTML или задать каждому элементу новое значение.

В данном уроке мы рассмотрим конструкцию foreach при организации цикла по индексированным и ассоциированным массивам.

Цикл по значениям элементов

Самый простой случай использования foreach — это организация цикла по значениям в индексированном массиве. Основной синтаксис :

foreach ( $array as $value ) < // Делаем что-нибудь с $value >// Здесь код выполняется после завершения цикла

Например, следующий скрипт проходит по списку режисеров в индексированном массиве и выводит имя каждого:

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); foreach ( $directors as $director ) < echo $director . "
"; >

Выше приведенный код выведет:

Alfred Hitchcock Stanley Kubrick Martin Scorsese Fritz Lang

Цикл по ключам и значениям

А что насчет ассоциированных массивов? При использовании такого типа массивов часто нужно иметь доступ к ключу каждого элемента, так же как и к его значению. Конструкция foreach имеет способ решить поставленную задачу:

foreach ( $array as $key => $value ) < // Делаем что-нибудь с $key и/или с $value >// Здесь код выполняется после завершения цикла

Пример организации цикла по ассоциированному массиву с информацией о кинофильмах, выводит ключ каждого элемента и его значение в HTML списке определений:

$movie = array( "title" => "Rear Window", "director" => "Alfred Hitchcock", "year" => 1954, "minutes" => 112 ); echo "
"; foreach ( $movie as $key => $value ) < echo "
$key:
"; echo "
$value
"; > echo "
";

Данный скрипт при выполнении выведет:

title: Rear Window director: Alfred Hitchcock year: 1954 minutes: 112

Изменение значения элемента

А как обстоит дело с изменением значения элемента при проходе цикла? Вы можете попробовать такой код:

foreach ( $myArray as $value )

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

Для изменения значений массива вам нужна ссылка на значение. Для этого нужно поставить знак & перед переменной значения в конструкции foreach :

foreach ( $myArray as &$value )

$value становится ссылкой на значение элемента в оригинальном массиве, а значит, вы можете изменять элемент устанавливая новое значение в $value .

— это указатель на оригинальное значение. Она похожа на ярлык в Windows, или на псевдоним в Mac OS.

Например, следующий скрипт проходит циклом каждый элемент (имя режиссера) в массиве $directors , и использует функцию PHP explode() и конструкцию list для перемены мест имени и фамилии:

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ); // Изменяем формат имени для каждого элемента foreach ( $directors as &$director ) < list( $firstName, $lastName ) = explode( " ", $director ); $director = "$lastName, $firstName"; >unset( $director ); // Выводим конечный результат foreach ( $directors as $director ) < echo $director . "
"; >
Hitchcock, Alfred Kubrick, Stanley Scorsese, Martin Lang, Fritz

Отметим, что скрипт вызывает функцию unset() для удаления переменной $director после завершения первого цикла. Это хорошая практика, если вы планируете использовать переменную позже в скрипте в другом контексте.

Читайте также:  Jmenu in java swing

Если не удалять ссылку, то есть риск при дальнейшем выполнении кода случайной ссылки на последний элемент в массиве («Lang, Fritz»), если далее использовать переменную $director , что приведет к непредвиденным последствиям!

В данном уроке мы рассмотрели, как использовать конструкцию PHP foreach для организации цикла по элементам массива. Были рассмотрены вопросы:

  • Как организовать цикл по элементам массива
  • Как получить доступ к ключу и значению каждого элемента
  • Как использовать ссылку для изменения значений при проходе цикла

Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: www.elated.com/articles/foreach-loop-through-php-arrays/
Перевел: Сергей Фастунов
Урок создан: 20 Августа 2010
Просмотров: 162438
Правила перепечатки

5 последних уроков рубрики «PHP»

Фильтрация данных с помощью zend-filter

Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

Контекстное экранирование с помощью zend-escaper

Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

Подключение Zend модулей к Expressive

Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

Совет: отправка информации в Google Analytics через API

Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

Подборка PHP песочниц

Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

Источник

For each key value php

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:

Читайте также:  Java connection utf 8

// 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:

Источник

For each key value php

Beware of how works iterator in PHP if you come from Java!

In Java, iterator works like this :
interface Iterator < O > boolean hasNext ();
O next ();
void remove ();
>
?>
But in php, the interface is this (I kept the generics and type because it’s easier to understand)

Читайте также:  Http webpass simplegate ru login html

interface Iterator < O > boolean valid ();
mixed key ();
O current ();
void next ();
void previous ();
void rewind ();
>
?>

1. valid() is more or less the equivalent of hasNext()
2. next() is not the equivalent of java next(). It returns nothing, while Java next() method return the next object, and move to next object in Collections. PHP’s next() method will simply move forward.

Here is a sample with an array, first in java, then in php :

class ArrayIterator < O >implements Iterator < O > private final O [] array;
private int index = 0 ;

public ArrayIterator ( O [] array) this .array = array;
>

public boolean hasNext () return index < array. length ;
>

public O next () if ( ! hasNext ())
throw new NoSuchElementException ( ‘at end of array’ );
return array[ index ++];
>

public void remove () throw new UnsupportedOperationException ( ‘remove() not supported in array’ );
>
>
?>

And here is the same in php (using the appropriate function) :

/**
* Since the array is not mutable, it should use an internal
* index over the number of elements for the previous/next
* validation.
*/
class ArrayIterator implements Iterator private $array ;
public function __construct ( $array ) if ( ! is_array ( $array ))
throw new IllegalArgumentException ( ‘argument 0 is not an array’ );
$this -> array = array;
$this -> rewind ();
>
public function valid () return current ( $this -> array ) !== false ;
// that’s the bad method (should use arrays_keys, + index)
>
public function key () return key ( $this -> array );
>
public function current () return current ( $this -> array );
>
public function next () if ( $this -> valid ())
throw new NoSuchElementException ( ‘at end of array’ );
next ( $this -> array );
>
public function previous () // fails if current() = first item of array
previous ( $this -> array );
>
public function rewind () reset ( $this -> array );
>
>
?>

The difference is notable : don’t expect next() to return something like in Java, instead use current(). This also means that you have to prefetch your collection to set the current() object. For instance, if you try to make a Directory iterator (like the one provided by PECL), rewind should invoke next() to set the first element and so on. (and the constructor should call rewind())

class ArrayIterable < O >implements Iterable < O > private final O [] array;

public ArrayIterable ( O [] array) this .array = array;
>

public Iterator < O >iterator () return new ArrayIterator (array);
>
>
?>

When using an Iterable, in Java 1.5, you may do such loops :

for ( String s : new ArrayIterable < String >(new String [] < "a" , "b" >)) .
>
?>
Which is the same as :

Iterator < String >it = new ArrayIterable < String >(new String [] < "a" , "b" >);
while ( it . hasNext ()) String s = it . next ();
.
>
?>
While in PHP it’s not the case :
foreach ( $iterator as $current ) .
>
?>
Is the same as :

for ( $iterator -> rewind (); $iterator -> valid (); $iterator -> next ()) $current = $iterator -> current ();
.
>
?>

(I think we may also use IteratorAggregate to do it like with Iterable).

Take that in mind if you come from Java.

I hope this explanation is not too long.

Источник

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