Php работа с массивами в цикле

Php работа с массивами в цикле thumbnail

foreach

(PHP 4, PHP 5, PHP 7, PHP 8)

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

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

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

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

Обратите внимание, что foreach не изменяет указатель внутреннего массива, который используется такими функциями, как current() и key().

Возможно настроить итераторы объектов.

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

<?php

$arr = array(1, 2, 3, 4);

foreach ($arr as &$value) {

$value = $value * 2;

}

// массив $arr сейчас таков: array(2, 4, 6, 8)

unset($value); // разорвать ссылку на последний элемент

?>

Внимание

Ссылка $value на последний элемент массива останется после окончания цикла foreach. Рекомендуется уничтожать её с помощью unset(). В противном случае вы можете столкнуться с таким поведением:

<?php

$arr = array(1, 2, 3, 4);

foreach ($arr as &$value) {

$value = $value * 2;

}

// $arr = array(2, 4, 6, 8)

// Без unset($value), $value всё ещё ссылается на последний элемент: $arr[3]

foreach ($arr as $key => $value) {

// $arr[3] будет перезаписываться значениями $arr при каждой итерации цикла

echo “{$key} => {$value} “;

_r($arr);

}

// …И в конце концов предпоследнее значение определит окончательное содержимое $arr[3]

// вывод:

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

?>

Можно перебирать значение постоянного массива по ссылке:

<?php

foreach (array(1, 2, 3, 4) as &$value) {

$value = $value * 2;

}

?>

Замечание:

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

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

<?php

/* Пример 1: только значение */$a = array(1, 2, 3, 17);

foreach (

$a as $v) {

echo “Текущее значение переменной $a: $v.n”;

}/* Пример 2: значение (для иллюстрации массив выводится в виде значения с ключом) */$a = array(1, 2, 3, 17);$i = 0; /* только для пояснения */foreach ($a as $v) {

echo “$a[$i] => $v.n”;

$i++;

}/* Пример 3: ключ и значение */$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 “$v2n”;

}

}/* Пример 5: динамические массивы */foreach (array(1, 2, 3, 4, 5) as $v) {

echo “$vn”;

}

?>

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

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

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

Например:

<?php

$array = [

[1, 2],

[3, 4],

];

foreach (

$array as list($a, $b)) {

// $a содержит первый элемент вложенного массива,

// а $b содержит второй элемент.

echo “A: $a; B: $bn”;

}

?>

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

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

<?php

$array = [

[1, 2],

[3, 4],

];

foreach (

$array as list($a)) {

// Обратите внимание на отсутствие $b.

echo “$an”;

}

?>

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

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

<?php

$array = [

[1, 2],

[3, 4],

];

foreach (

$array as list($a, $b, $c)) {

echo “A: $a; B: $b; C: $cn”;

}

?>

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

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:

adam dot sindelar at gmail dot com ¶

13 years ago

You can also use the alternative syntax for the foreach cycle:

<?php

foreach($array as $element):

endforeach;

?>

Just thought it worth mentioning.

php at darkain dot com ¶

8 years ago

“Reference of a $value and the last array element remain even after the foreach loop. It is ed to destroy it by unset().”

I cannot stress this point of the documentation enough! Here is a simple example of exactly why this must be done:

<?php

$arr1 = array(“a” => 1, “b” => 2, “c” => 3);

$arr2 = array(“x” => 4, “y” => 5, “z” => 6);

foreach (

$arr1 as $key => &$val) {}

foreach ($arr2 as $key => $val) {}var_dump($arr1);

var_dump($arr2);

?>

The output is:

array(3) { [“a”]=> int(1) [“b”]=> int(2) [“c”]=> &int(6) }

array(3) { [“x”]=> int(4) [“y”]=> int(5) [“z”]=> int(6) }

Notice how the last index in $arr1 is now the value from the last index in $arr2!

KEINOS ¶

3 years ago

Even though it is not mentioned in this article, you can use “break” control structure to exit from the “foreach” loop.

<?php

$array

= [ ‘one’, ‘two’, ‘three’, ‘four’, ‘five’ ];

foreach(

$array as $value ){

if( $value == ‘three’ ){

echo “Number three was found!”;

break;

}

}?>

mparsa1372 at gmail dot com ¶

2 months ago

Examples

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

<?php

$colors = array(“red”, “green”, “blue”, “yellow”);

foreach (

$colors as $value) {

echo “$value <br>”;

}

?>

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

Example

<?php

$age = array(“Peter”=>”35”, “Ben”=>”37”, “Joe”=>”43”);

foreach(

$age as $x => $val) {

echo “$x = $val<br>”;

}

?>

John ¶

4 years ago

WARNING: Looping through “values by reference” for ” performance” is an old myth. It’s actually WORSE!

<?php one($arr) {

foreach($arr as $val) { echo $val;

}

}

two($arr) {

foreach($arr as &$val) { echo $val;

}

}$a = array( ‘a’, ‘b’, ‘c’ );

one($a);

two($a);?>

Which do you think is faster?

Lots of people think the answer is two() because it uses “reference to value, which it doesn’t have to copy each value when it loops”.

Well, that’s totally wrong!

Here’s what actually happens:

* one():

– This takes an array as argument ($arr).

– The array argument itself isn’t passed by reference, so the knows it isn’t allowed to modify the original at all.

– Then the foreach loop happens. The array itself wasn’t passed by reference to the , so PHP knows that it isn’t allowed to modify the outside array, so it therefore makes a copy of the array’s internal iteration offset e (that’s just a simple number which says which item you are currently at during things like foreach()), which costs almost no performance or memory at all since it’s just a small number.

– Next, it uses that copied iteration offset to loop through all key/value pairs of the array (ie 0th key, 1st key, 2nd key, etc…). And the value at the current offset (a PHP “zval”) is ased to a variable called $val.

Читайте также:  Сбои менструального цикла после 40 лет

– Does $val make a COPY of the value? That’s what MANY people think. But the answer is NO. It DOESN’T. It re-uses the existing value in memory. With zero performance cost. It’s called “copy-on-write” and means that PHP doesn’t make any copies unless you try to MODIFY the value.

– If you try to MODIFY $val, THEN it will allocate a NEW zval in memory and store $val there instead (but it still won’t modify the original array, so you can rest assured).

Alright, so what’s the second version doing? The beloved “iterate values by reference”?

* two():

– This takes an array as argument ($arr).

– The array argument itself isn’t passed by reference, so the knows it isn’t allowed to modify the original at all.

– Then the foreach loop happens. The array itself wasn’t passed by reference to the , so PHP knows that it isn’t allowed to modify the outside array.

– But it also sees that you want to look at all VALUES by reference (&$val), so PHP says “Uh oh, this is dangerous. If we just give them references to the original array’s values, and they as some new value to their reference, they would destroy the original array which they aren’t allowed to touch!”.

– So PHP makes a FULL COPY of the ENTIRE array and ALL VALUES before it starts iterating. YIKES!

Therefore: STOP using the old, mythological “&$val” iteration method! It’s almost always BAD! With worse performance, and risks of bugs and quirks as is demonstrated in the manual.

You can always manually write array asments explicitly, without references, like this:

<?php

$a

= array(1, 2, 3);

foreach($a as $key => $val) {

$a[$key] = $val * 10;

}

?>

The main lesson is this: DON’T blindly iterate through values by reference! Telling PHP that you want direct references will force PHP to need to copy the WHOLE array to protect its original values! So instead, just loop normally and trust the fact that PHP *is* actually smart enough to never copy your original array’s values! PHP uses “copy-on-write”, which means that attempting to as something new to $val is the ONLY thing that causes a copying, and only of that element! 🙂 But you never do that anyway, when iterating without reference. If you ever want to modify something, you use the “$a[$key] = 123;” method of updating the value.

Enjoy and good luck with your code! 🙂

tedivm at tedivm dot com ¶

12 years ago

foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other.

<?php

$arr = array(1,2,3,4,5,6,7,8,9);

foreach(

$arr as $key=>$value)

{

unset($arr[$key + 1]);

echo $value . PHP_EOL;

}

?>

Output:

1 2 3 4 5 6 7 8 9

<?php

$arr = array(1,2,3,4,5,6,7,8,9);

while (list(

$key, $value) = each($arr))

{

unset($arr[$key + 1]);

echo $value . PHP_EOL;

}

?>

Output:

1 3 5 7 9

[EDIT BY danbrown AT php DOT net: Contains a typofix by (scissor AT phplabs DOT pl) on 30-JAN-2009.]

Fred ¶

6 years ago

If you want to use the list for multidimension arrays, you can nest several lists:

<?php

$array = [

[1, 2, array(3, 4)],

[3, 4, array(5, 6)],

];

foreach (

$array as list($a, $b, list($c, $d))) {

echo “A: $a; B: $b; C: $c; D: $d;<br>”;

};

?>

Will output:

A: 1; B: 2; C: 3; D: 4;

A: 3; B: 4; C: 5; D: 6;

And:

<?php

$array = [

[1, 2, array(3, array(4, 5))],

[3, 4, array(5, array(6, 7))],

];

foreach (

$array as list($a, $b, list($c, list($d, $e)))) {

echo “A: $a; B: $b; C: $c; D: $d; E: $e;<br>”;

};

Will output:

A: 1; B: 2; C: 3; D: 4; E: 5;

A: 3; B: 4; C: 5; D: 6; E: 7;

?>

mustaroad ¶

4 years ago

in foreach if you want to iterate through a specific column in a nested arrays for example:

$arr = array(

[1, 2, 3, 4],

[14, 6, 7, 6],

[10, 2 ,3 , 2],

);

when we want to iterate on the third column we can use:

foreach( $arr as list( , , $a)) {

echo “$an”;

}

this will :

3

7

3

Alastair Hole ¶

7 years ago

What happened to this note:

“Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don’t rely on the array pointer during or after the foreach without resetting it.”

Is this no longer the case?

It seems only to remain in the Serbian documentation: https://php.net/manual/sr/control-structures.foreach.php

Oleg englishman at bigmir dot net ¶

10 years ago

For those who’d like to traverse an array including just added elements (within this very foreach), here’s a workaround:

<?php

$values = array(1 => ‘a’, 2 => ‘b’, 3 => ‘c’);

while (list($key, $value) = each($values)) {

echo “$key => $value rn”;

if ($key == 3) {

$values[4] = ‘d’;

}

if ($key == 4) {

$values[5] = ‘e’;

}

}

?>

the code above will output:

1 => a

2 => b

3 => c

4 => d

5 => e

Delian Krustev ¶

7 years ago

I want to add some inline s to dtowell’s piece of code the iteration by reference:

<?php

$a

= array(‘abe’,’ben’,’cam’);

foreach (

$a as $k=>&$n)

$n = strtoupper($n);foreach ($a as $k=>$n) echo “$nn”;_r($a);

?>

peter georgiev ¶

3 years ago

I want just to mention that John is not entirely true.

Simple field test:

$m = micro(1); $array = range(1,1000000); foreach ($array as &$i) { $i = 4; } echo micro(1) – $m;

Result: 0.21731400489807

$m = micro(1); $array = range(1,1000000); foreach ($array as $k => $i) { $array[$k] = 4; } echo micro(1) – $m;

Result: 0.51596283912659

PHP Version: PHP 5.6.30 (cli) (built: Jan 18 2017 19:47:36)

Conclusion: Working with reference, although a bit dangerous is >2 s faster. You just need to know well what are you doing.

Best of luck and happy coding all

sebastian dot goendoer at NOSPAM dot telekom dot de ¶

5 years ago

String keys of associative arrays, for which is_numeric() is true and which can be type-juggled to an int will be cast to an int! If the key is on the other hand a string that can be type-juggled into a float, it will stay a string. (Observed on PHP 7.0.0RC8)

<?php

$arr = array();

$arr[0] = “zero”; $arr[“1”] = “one”; $arr[“two”] = “2”; $arr[“3.5”] = “threeandahalf”; foreach($arr as $key => $value) {

var_dump($key);

}

?>

The output will be

int(0)

int(1)

string(3) “two”

string(3) “3.5”

Anonymous ¶

6 years ago

modifying array while foreach’ing it(yeah, such slime code;-)

if elements were added on last iteration or into array with 1 element, then added elements wont be iterated as foreach checks for pointer before iteration cycle

so it just quit and added elements wont be treated

nehuen ¶

7 years ago

foreach by reference internally deleted and created a new reference in each iteration, so it is not possible to directly use this value as a variable parameter values​​, look at the following example where the problem is observed and a possible solution:

Читайте также:  Шарманщик шуберт из цикла зимний путь

<?php

class test

{

private $a = false;

private $r = null;

public show(&$v)

{

if(!$this->a)

{

$this->a = true;

$this->r = &$v;

}

var_dump($this->r);

}

public reset()

{

$this->a = false;

}

}$t = new test();$a = array(array(1,2),array(3,4),array(5,6));

foreach($a as &$p)

$t->show($p);

$t->reset();

foreach($a as $p)

{

$b = &$p;

$t->show($b);

}

ahmad dot mayahi at gmail dot com ¶

4 years ago

foreach retains the e of internal defined variable:

<?php

$arr = [“a”, “b”, “c”];

$title = “”;

foreach ($arr as $r) {

if ($r == “a”) {

$title = “Hello World”;

}

echo $title.”<br>”;

}

?>

in this case, all we need to do is to add an else ement:

<?php

$arr = [“a”, “b”, “c”];

$title = “”;

foreach ($arr as $r) {

if ($r == “a”) {

$title = “Hello World”;

} else {

$title = “”;

}

echo $title.”<br>”;

}

?>

nobody at nobody dot com ¶

9 years ago

<?php

$d3 = array(‘a’=>array(‘b’=>’c’));

foreach($d3[‘a’] as &$v4){}

foreach($d3 as $v4){}

var_dump($d3);

?>

will get something look like this:

array(1) {

[“a”]=>

array(1) {

[“b”]=>

&array(1) {

[“b”]=>

*RECURSION*

}

}

}

then you try to walk some data with this array.

the script run out of memory and connect reset by peer

the document says:

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is ed to destroy it by unset().

so what I learn is that NEVER “””Warning””” in document….

pnc at balintx dot me ¶

5 years ago

Just a simple strange behavior I have ran into:

If you accidentally put a semicolon after the foreach ement, you get no errors, but the loop will only run on the last element of the array:

<?php

$array = array(1,2,3);

foreach ($array as $key);

{

echo $key;

}

?>

Correctly:

<?php

$array = array(1,2,3);

foreach ($array as $key)

{

echo $key;

}

?>

It took me a while to find that semicolon.

dan ¶

1 year ago

Having to unset the reference manually completely destroys the practicality of using a referenced variable.

If you make the small mistake of forgetting/deleting the unset line your code might silently mix data, the risk is too high for little gain.

If you need to reas the value, it is way better to just use:

<?php

$array[$key] = $newvalue;

?>

M H S ¶

1 year ago

<?php

$arr

= [“one” => 1, “two” => 2];

$arr2 = [];

foreach (

$arr as $key => $value) {

foreach ($arr as $key2 => $value2) {

if ($arr[$key] == $value2) continue; else $arr2[$key2] = $value;

}

}

echo

“<pre>”;

_r ($arr2 !== $arr ? $arr2 : false);

echo “</pre>”;?>

Ashus ¶

8 years ago

If you wondered how to create a list of all possible combinations of variable amount of arrays (multiple foreach), you might use this:

<?php

$a

[0] = array(‘a1′,’a2’);

$a[1] = array(‘b1′,’b2′,’b3’);

$a[2] = array(‘c1′,’c2’); getAllCombinations($a,$i,$s)

{

foreach ($a[$i] as $v)

{

if (!isset($a[$i+1]))

{

echo $s.$v.”n”;

} else {

getAllCombinations($a,$i+1,$s.$v);

}

}

return $s;

}

echo

getAllCombinations($a,0,”);?>

the result:

a1b1c1

a1b1c2

a1b2c1

a1b2c2

a1b3c1

a1b3c2

a2b1c1

a2b1c2

a2b2c1

a2b2c2

a2b3c1

a2b3c2

liam666 at donnelly-house dot net ¶

6 years ago

This is a decent, simple, and easy way to reference other values of an associative array when using foreach. (effective “next”, “prev”, etc.)

The only care that needs to be taken is if the array is HUGE in size, so you don’t run into memory use problems. (and potential speed issues)

This example uses the ‘primary’ array, $aPublishSeq, which is ksort-ed to put the array in order according to the associative keys. The array is then copied using a foreach loop to make a duplicate array where the key and value order correspond to the first array, but the keys are sequential numeric starting at zero.

ksort ($aPublishSeq, SORT_STRING); // put them all in the right order keeping array keys

foreach ($aPublishSeq as $aValue)

$aPublishIdx[] = $aValue; // duplicate array using corresponding sequential numeric keys

Now, in the usage foreach loop, an index variable is used to keep in sync with the associative array.

$PubIdx = -1; // start at -1 to start at 0 below

foreach ($aPublishSeq as $sKey => $sValue) {

++$PubIdx; // index into $aPublishIdx array of corresponding element in $aPublishSeq array (for “next” element check, etc.)

echo $aPublishIdx[$PubIdx – 1] // previous array value

echo $aPublishIdx[$PubIdx] // current array value

echo $aPublishIdx[$PubIdx + 1] // next array value

….

It’s simple, but it works, and without much muss or fuss.

me ¶

10 months ago

It is not documented, but when modifying the array within foreach:

PHP seems to create a snapshot, or a copy of the entire array (“copy on write”?) when it starts the foreach loop, so changes on the iterated array in the loop have no effect on the started loop.

$a = [1,2,3];

foreach ($a as $key => $value) {

if($value == 1) {

$a[3] = 1;

$a[1] = 999999;

unset($a[0]);

echo “Inner loop start: n”;

foreach ($a as $key2 => $value2) {

echo “$key2 => $value2”;

echo “n”;

}

echo “Inner loop end n”;

}

echo “$key => $value”;

echo “n”;

}

echo “Next iteration: n”;

foreach ($a as $key => $value) {

echo “$key => $value”;

echo “n”;

}

Result:

Inner loop start:

1 => 999999

2 => 3

3 => 1

Inner loop end

0 => 1

1 => 2

2 => 3

Next iteration:

1 => 999999

2 => 3

3 => 1

Voitcus at wp dot pl ¶

9 years ago

You can even iterate through “dynamic” arrays that do not physically exist, but are objects that implement Iterator interface. They don’t need to be stored in memory when foreach starts.

Consider the array that contains some values (I called it $allValues in the example below) and we want to have only some of them (eg. the ones that are dividable by 2). I create an object that would serve as dynamic array, that means it would “dynamically up” its values together with $allValues. The main advantage is that I store only one array, and it’s the only array I serialize.

An object of MyIter class will not contain any values itself:

<?php

class MyIter implements Iterator { private $position = 0; private getTable(){ global $allValues;

$result=array(); foreach($allValues as $obj){

if($obj % 2 == 0) $result[]=$obj; }

return $result;

} rewind() { $this->position = 0; }

current() { $table=$this->getTable(); return $table[$this->position]; } key() { return $this->position; } next() { ++$this->position;

} valid() { return array_key_exists($this->position, $this->getTable());

}

} $allValues=array(0,1,2,3,4,5,6,7,8,9,10,11);$iterator=new MyIter();

foreach(

$iterator as $value){

echo $value.”<br />”;

}

?>

This will result in:

2

4

6

8

10

(You may also like to see what var_dump($iterator) produces).

Another great advantage is that you can modify the main table “on-the-fly” and it has its impact. Let us modify the last foreach loop:

<?php

foreach($iterator as $value){

echo $value.”<br />”;

if($value==6){

$allValues=array(2,3);

echo “I modified source array!<br />”;

}

}

?>

This produces now:

2

4

6

I modified source array!

However, if you feel it is rather a catastrophic disadvantage (maybe for example, it shows the values 0, 4, and 6 which were removed when we reached 6), and wish to have a “ic” array that will iterate even in modified objects, just call getTable() in rewind() method and save it in temporary (private perhaps) field. In my example getTable() is called every iteration, and it calls another foreach through $allValues, which together might be -consuming. Consider what you need.

Читайте также:  Если перестать пить противозачаточные в начале цикла

luqh555 at gmail dot com ¶

1 year ago

Here is an example of how to a 2 dimension array.

$agenda =array(“fulanito”=> array(“nombre” =>”Gsancho” ,

“direccion” => “sierra olvira” ,

“fuerza” => “Over 9000”) ,

“jonki” => array(“nombre” => “jonki”,

“direccion” => “valdemin”,

“fuerza” => “0”));

foreach($agenda as $clave_agenda =>$persona){

echo “$clave_agenda “;

foreach($persona as $clave_agenda2 => $datos){

echo “$clave_agenda2 : $datos <br>”;

}

Источник

Работа с массивами PHP – создание, наполнение, удаление

Основные примеры работы с массивами PHP. Создание, наполнение, извлечение удаление значений.

1

Создание массивов

Создать массив и заполнить его значениями

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); // или $array = array(); $array[] = ‘яблоко’; $array[] = ‘апельсин’; $array[] = ‘виноград’;

PHP

Можно применить функцию array_fill($start, $size, $value), которая создаст массив с количеством $size элементов со значением $value, начиная с индекса $start.

Данный пример создает массив с тремя элементам «текст», ключи которых будут начинаться с нуля.

$array = array_fill(0, 3, ‘текст’); _r($array);

PHP

Результат:

Array ( [0] => текст [1] => текст [2] => текст )

Еще вариант – функция explode($delimiter, $string), которая из строки $string создаст массив используя разделитель $delimiter, в данном примере запятая.

$array = explode(‘,’, ‘текст 1,текст 2,текст 3’); _r($array);

PHP

Результат:

Array ( [0] => текст 1 [1] => текст 2 [2] => текст 3 )

2

Узнать количество элементов в массиве

echo count($array); // или echo sizeof($array);

PHP

Если массив ассоциативный (многомерный), то count() вернёт количество элементов только первого уровня. Чтобы получит количество всех элементов нужно использовать константу COUNT_RECURSIVE.

$array = array( array( ‘яблоко’, ‘апельсин’, ‘виноград’ ), array( ‘яблоко’, ‘апельсин’, ‘виноград’ ) ); echo count($array); // вернет 2 echo count($array, COUNT_RECURSIVE); // вернет 8

PHP

3

Добавление элементов в массив

Добавить значение в начало массива

array_unshift($array, $value) – добавляет одно или несколько элементов в начало массива.

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); array_unshift($array, ‘банан’); _r($array);

PHP

Результат:

Array ( [0] => банан [1] => яблоко [2] => апельсин [3] => виноград )

Добавить значение в конец массива

array_push($array, $value) – добавляет значение в конец массива.

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); array_push($array, ‘банан’); // или $array[] = ‘банан’; _r($array);

PHP

Результат:

Array ( [0] => яблоко [1] => апельсин [2] => виноград [3] => банан [4] => банан )

4

Получение данных из массива

Получить первый элемент массива

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); reset($array); $first = current($array); // яблоко

PHP

Получить последний элемент массива

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); $end = end($array); // виноград

PHP

Получить часть (срез) массива

array_slice($array, $offset, $length) возвращает часть массива начиная с индекса $offset длиной $length.

  • Если $offset отрицательный, то отчет начинается с конца массива.
  • $length можно не указывать, тогда функция вернет все элементы до конца массива начиная с индекса $offset.

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); $new = array_slice($array, 0, 2); _r($new);

PHP

Результат:

Array ( [0] => яблоко [1] => апельсин )

Извлечь первый элемент массива

array_shift($array) – извлекает первый элемент из массива $array и возвращает его значение.

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); $first = array_shift($array); // яблоко _r($array);

PHP

Результат:

Array ( [0] => апельсин [1] => виноград )

Извлечь последний элемент массива

array_pop($array) – извлекает последний элемент из массива $array и возвращает его значение.

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); $end = array_pop($array); // виноград _r($array);

PHP

Результат:

Array ( [0] => яблоко [1] => апельсин )

Извлечь часть массива

Чтобы извлечь из массива часть можно применить функции array_slice() и array_diff().

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); $new = array_slice($array, 0, 2); $array = array_diff($array, $new); _r($new); _r($array);

PHP

Результат:

Array ( [0] => яблоко [1] => апельсин ) Array ( [2] => виноград )

Выбрать все значения из массива

array_values($array) – создает новый массив из исходного $array игнорируя его ключи.

$array = array( ‘key 1’ => ‘яблоко’, ‘key 2’ => ‘апельсин’, ‘key 3’ => ‘виноград’ ); $new = array_values($array); _r($new);

PHP

Результат:

Array ( [0] => яблоко [1] => апельсин [2] => виноград )

Выбрать все ключи массива

array_keys($array) – создает новый массив состоящий из ключей исходного массива.

$array = array( ‘key 1’ => ‘яблоко’, ‘key 2’ => ‘апельсин’, ‘key 3’ => ‘виноград’ ); $new = array_keys($array); _r($new);

PHP

Результат:

Array ( [0] => key 1 [1] => key 2 [2] => key 3 )

Выбирать случайные значения из массива

array_rand($array, $count) возвращает случайным образом один или несколько ключей из массива $array. Если $count больше единицы, то результат будет в виде массива.

$array = array( 3 => ‘яблоко’, 1 => ‘апельсин’, 5 => ‘виноград’ ); echo $array[array_rand($array)];

PHP

5

Поиск и проверка элементов в массиве

Проверить, есть ли значение в массиве

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); if (in_array(‘апельсин’, $array)) { echo ‘Найдено значение “апельсин”‘; } // или if (array_(‘апельсин’, $array) !== false) { echo ‘Найдено значение “апельсин”‘; }

PHP

Проверить, есть ли ключ в массиве

$array = array( 1 => ‘яблоко’, 2 => ‘апельсин’, 3 => ‘виноград’ ); if (array_key_exists(2, $array)) { echo ‘Найден ключ 2’; } // или if (isset($array[2])) { echo ‘Найден ключ 2’; }

PHP

6

Удаление элементов из массива

unset() – удаляет переменные и элементы массива по ключу.

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

$array = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); // Удаление по ключу unset($array[1]); // Удаление по значению unset($array[array_(‘апельсин’, $array)]); _r($array);

PHP

Результат:

Array ( [0] => яблоко [2] => виноград )

Удаление пустых значений

В PHP нет отдельной функции для удаления пустых значений в массиве, поэтому применяют array_diff() которая возвращает расхождения массивов.

$array = array( ‘яблоко’, ”, ‘виноград’ ); $array = array_diff($array, array(”)); _r($array);

PHP

Результат:

Array ( [0] => яблоко [2] => виноград )

Если требуется удалить значения включая 0, null, array() и т.д. можно применить следующее:

$array = array_diff($array, array(”, ‘ ‘, null, 0, array()));

PHP

Удалить повторяющиеся значения массива

$array = array( ‘яблоко’, ‘яблоко’, ‘апельсин’, ‘виноград’ ); $array = array_unique($array); _r($array);

PHP

Результат:

Array ( [0] => яблоко [2] => апельсин [3] => виноград )

7

Объединение массивов

Объединить два и более массивов поможет функция array_merge($array_1, $array_2, …).

$array_1 = array( ‘яблоко’, ‘апельсин’, ‘виноград’ ); $array_2 = array( ‘помидор’, ‘огурец’, ); $new = array_merge($array_1, $array_2); _r($new);

PHP

Результат:

Array ( [0] => яблоко [1] => апельсин [2] => виноград [3] => помидор [4] => огурец )

8

Разделить массив на части

array_chunk($array, $size) – создает новый многомерный массив из исходного, деля его на равные части.

В данном примере указано $size = 3, поэтому получается четыре подмассива в каждом из которых по три элемента.

$array = array( ‘январь’, ‘февраль’, ‘март’, ‘апрель’, ‘май’, ‘июнь’, ‘июль’, ‘август’, ‘сентябрь’, ‘ноябрь’, ‘декабрь’, ); $array = array_chunk($array, 3); _r($array);

PHP

Результат:

Array ( [0] => Array ( [0] => январь [1] => февраль [2] => март ) [1] => Array ( [0] => апрель [1] => май [2] => июнь ) [2] => Array ( [0] => июль [1] => август [2] => сентябрь ) [3] => Array ( [0] => ноябрь [1] => декабрь ) )

Если требуется разделить массив на определенное количество частей поможет следующий прием:

$array = array( ‘январь’, ‘февраль’, ‘март’, ‘апрель’, ‘май’, ‘июнь’, ‘июль’, ‘август’, ‘сентябрь’, ‘ноябрь’, ‘декабрь’, ); $array = array_chunk($array, ceil(count($array) / 3)); _r($array);

PHP

Результат:

Array ( [0] => Array ( [0] => январь [1] => февраль [2] => март [3] => апрель ) [1] => Array ( [0] => май [1] => июнь [2] => июль [3] => август ) [2] => Array ( [0] => сентябрь [1] => ноябрь [2] => декабрь ) )

Источник