PHP 7.0.26 Released

Операторы, работающие с массивами

Операторы, работающие с массивами
Пример Название Результат
$a + $b Объединение Объединение массива $a и массива $b.
$a == $b Равно TRUE в случае, если $a и $b содержат одни и те же пары ключ/значение.
$a === $b Тождественно равно TRUE в случае, если $a и $b содержат одни и те же пары ключ/значение в том же самом порядке и того же типа.
$a != $b Не равно TRUE, если массив $a не равен массиву $b.
$a <> $b Не равно TRUE, если массив $a не равен массиву $b.
$a !== $b Тождественно не равно TRUE, если массив $a не равен тождественно массиву $b.

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

<?php
$a 
= array("a" => "apple""b" => "banana");
$b = array("a" => "pear""b" => "strawberry""c" => "cherry");

$c $a $b// Объединение $a и $b
echo "Union of \$a and \$b: \n";
var_dump($c);

$c $b $a// Объединение $b и $a
echo "Union of \$b and \$a: \n";
var_dump($c);

$a += $b// Объединение $a += $b, это $a и $b
echo "Объединение of \$a += \$b: \n";
var_dump($a);
?>
После своего выполнения скрипт напечатает следующее:
Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}

Объединение $a += $b:
array(3) {
  'a' =>
  string(5) "apple"
  'b' =>
  string(6) "banana"
  'c' =>
  string(6) "cherry"
}

При сравнении элементы массива считаются идентичными, если совпадает и ключ, и соответствующее ему значение.

Пример #1 Сравнение массивов

<?php
$a 
= array("apple""banana");
$b = array(=> "banana""0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

Также ознакомьтесь с разделами Массивы и Функции для работы с массивами.

add a note add a note

User Contributed Notes 13 notes

up
142
cb at netalyst dot com
9 years ago
The union operator did not behave as I thought it would on first glance. It implements a union (of sorts) based on the keys of the array, not on the values.

For instance:
<?php
$a
= array('one','two');
$b=array('three','four','five');

//not a union of arrays' values
echo '$a + $b : ';
print_r ($a + $b);

//a union of arrays' values
echo "array_unique(array_merge($a,$b)):";
// cribbed from http://oreilly.com/catalog/progphp/chapter/ch05.html
print_r (array_unique(array_merge($a,$b)));
?>

//output

$a + $b : Array
(
    [0] => one
    [1] => two
    [2] => five
)
array_unique(array_merge(Array,Array)):Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
)
up
20
Q1712 at online dot ms
10 years ago
The example may get u into thinking that the identical operator returns true because the key of apple is a string but that is not the case, cause if a string array key is the standart representation of a integer it's gets a numeral key automaticly.

The identical operator just requires that the keys are in the same order in both arrays:

<?php
$a
= array (0 => "apple", 1 => "banana");
$b = array (1 => "banana", 0 => "apple");

var_dump($a === $b); // prints bool(false) as well

$b = array ("0" => "apple", "1" => "banana");

var_dump($a === $b); // prints bool(true)
?>
up
12
dfranklin at fen dot com
13 years ago
Note that + will not renumber numeric array keys.  If you have two numeric arrays, and their indices overlap, + will use the first array's values for each numeric key, adding the 2nd array's values only where the first doesn't already have a value for that index.  Example:

$a = array('red', 'orange');
$b = array('yellow', 'green', 'blue');
$both = $a + $b;
var_dump($both);

Produces the output:

array(3) { [0]=>  string(3) "red" [1]=>  string(6) "orange" [2]=>  string(4) "blue" }

To get a 5-element array, use array_merge.

    Dan
up
8
Dan Patrick
5 years ago
It should be mentioned that the array union operator functions almost identically to array_replace with the exception that precedence of arguments is reversed.
up
2
csaba at alum dot mit dot edu
9 years ago
Simple array arithmetic:
A more compact way of adding or subtracting the elements at identical keys...

<?php
function array_add($a1, $a2) {  // ...
  // adds the values at identical keys together
 
$aRes = $a1;
  foreach (
array_slice(func_get_args(), 1) as $aRay) {
    foreach (
array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val;
   
$aRes += $aRay; }
  return
$aRes; }

function
array_subtract($a1, $a2) {  // ...
  // adds the values at identical keys together
 
$aRes = $a1;
  foreach (
array_slice(func_get_args(), 1) as $aRay) {
    foreach (
array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] -= $val;
    foreach (
array_diff_key($aRay, $aRes) as $key => $val) $aRes[$key] = -$val; }
  return
$aRes; }

Example:
$a1 = array(9, 8, 7);
$a2 = array(1=>7, 6, 5);
$a3 = array(2=>5, 4, 3);

$aSum = array_add($a1, $a2, $a3);
$aDiff = array_subtract($a1, $a2, $a3);

// $aSum  => [9, 15, 18, 9, 3]
// $aDiff => [9, 1, -4, -9, -3]
?>

To make a similar function, array_concatenate(), change only the first of the two '+=' in array_add() to '.='
Csaba Gabor from Vienna
up
-1
drone dot ah at gmail dot com
1 month ago
The note about array comparison by Q1712 is not entirely accurate.

"The identical operator just requires that the keys are in the same order in both arrays:"

This may have been the case in past (I cannot verify it). It requires that the keys are in the same order AND that the values match

To extend that example

<?php

  $a
= array (0 => "apple", 1 => "banana");
 
$b = array (1 => "banana", 0 => "apple");

 
var_dump($a === $b); // prints bool(false) as well

 
$b = array ("0" => "apple", "1" => "banana");

 
var_dump($a === $b); // prints bool(true)

 
$b = array ("0" => "apple-1", "1" => "banana-1");

 
var_dump($a === $b); // prints bool(false)

?>
up
-1
xtpeqii at Hotmail dot com
2 months ago
$a=[ 3, 2, 1];
$b=[ 6, 5, 4];
var_dump( $a + $b );

output:
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

The reason for the above output is that EVERY array in PHP is an associative one. 
Since the 3 elements in $b have the same keys( or numeric indices ) as those in $a, those elements in $b are ignored by the union operator.
up
1
amirlaher AT yahoo DOT co SPOT uk
14 years ago
[]= could be considered an Array Operator (in the same way that .= is a String Operator).
[]= pushes an element onto the end of an array, similar to array_push:
<?
  $array= array(0=>"Amir",1=>"needs");
  $array[]= "job";
  print_r($array);
?>
Prints: Array ( [0] => Amir [1] => needs [2] => job )
up
-6
kit dot lester at lycos dot co dot uk
12 years ago
When comparing arrays that have (some or all) element-values that are themselves array, then in PHP5 it seems that == and === are applied recursively - that is
* two arrays satisfy == if they have the same keys, and the values at each key satisfy == for whatever they happen to be (which might be arrays);
* two arrays satisfy === if they have the same keys, and the values at each key satisfy === for whatever (etc.).

Which explains what happens if we compare two arrays of arrays of arrays of...

Likewise, the corresponding inversions for != <> and !==.

I've tested this to array-of-array-of-array, which seems fairly convincing. I've not tried it in PHP4 or earlier.
up
-13
puneet singh @ value-one dot com
11 years ago
hi  just see one more example of union....

<?php
$a
= array(1,2,3);
$b = array(1,7,8,9,10);
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
//echo $c
print_r($c);
?>
//output
Union of $a and $b: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 10 )
up
-16
sd6733531 at gmail dot com
4 years ago
Look out use + with array combine.

$arr = array(1, 2, 3);
$int=345;
$arr=$arr+$int;

Of couse,use + to combine array is easy and readable.
But if one of the variable is not array type(like above code) ,that would make a PHP Fatal Error:
PHP Fatal error:  Unsupported operand types
Maybe should do check before.
up
-12
kit dot lester at lycos dot co dot uk
12 years ago
This manual page doesn't mention < & co for arrays, but example 15-2 in
    http://www.php.net/manual/en/language.operators.comparison.php
goes to some lengths to explain how they work.
up
-32
Anonymous
3 years ago
The manual say ...

"The + operator appends the right elements in the array from left, whereas duplicated keys are NOT overwritten"

but ..

$a = array("a" => 'A', "b" => 'B');
$b = array("a" => 'A', "b" => 'B', "c" => 'C');

$c = $a + $b // or $b + a  is  the same output;

echo '<pre>';

print_r($c);

echo '<pre>';

//Output   for  $a + b  or  $b + a
Array (
    [a] => A
    [b] => B
    [c] => C
)
To Top