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

Таблица 15-7. Операторы, работающие с массивами

ПримерНазваниеРезультат
$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);
?>

После своего выполнения скрипт напечатает следующее:
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"
}

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

Пример 15-3. Сравнение массивов

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

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

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



Операторы, работающие с массивами
puneet singh @ value-one dot com
18-Jan-2006 10:42
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 )
kit dot lester at lycos dot co dot uk
21-Aug-2005 09:01
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.
kit dot lester at lycos dot co dot uk
21-Aug-2005 08:44
This manual page doesn't mention < & co for arrays, but example 15-2 in
   manual/en/language.operators.comparison.php
goes to some lengths to explain how they work.
Peter
29-Oct-2004 07:57
The code from texbungalow at web dot de below is slightly incorrect.  If my memory from primary school history is correct, roman numerals don't allow things like MIM - it has to be MCMXCIX, ie each step is only 1 level down (sorry, I can't explain it very well.

a print_r($segments) comparing the snippets should explain.

Corrected code:
<?php
function roman ($nr ) {
    
$base_digits= array (
          
1=> "I",
          
10=> "X",
          
100=> "C",
          
1000=> "M",
           );
    
$help_digits= array (
          
5=> "V",
          
50=> "L",
          
500=> "D",
           );
    
$all_digits= $base_digits+ $help_digits;
     foreach (
$base_digits as $key1=> $value1 )
           foreach (
$all_digits as $key2=> $value2 )
                 if (
$key1< $key2 && $key1 >= ($key2 / 10))
                      
$segments[$key2- $key1 ]= $value1. $value2;
    
$segments+= $all_digits;
    
krsort ($segments );
     foreach (
$segments as $key=> $value )
           while (
$key<= $nr ) {
                
$nr-= $key;
                
$str.= $value;
                 }
     return
$str;
     }
echo
roman (1998);  //  prints MCMXCVIII
?>
dfranklin at fen dot com
22-Apr-2004 01:40
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
texbungalow at web dot de
26-Apr-2003 06:46
use '+=' to quickly append an array to another one:

function roman ($nr ) {
     $base_digits= array (
           1=> "I",
           10=> "X",
           100=> "C",
           1000=> "M",
           );
     $help_digits= array (
           5=> "V",
           50=> "L",
           500=> "D",
           );
     $all_digits= $base_digits+ $help_digits;
     foreach ($base_digits as $key1=> $value1 )
           foreach ($all_digits as $key2=> $value2 )
                 if ($key1< $key2 )
                       $segments[$key2- $key1 ]= $value1. $value2;
     $segments+= $all_digits;
     krsort ($segments );
     foreach ($segments as $key=> $value )
           while ($key<= $nr ) {
                 $nr-= $key;
                 $str.= $value;
                 }
     return $str;
     }

echo roman (888);  //  prints DCCCLXXXVIII
amirlaher AT yahoo DOT co SPOT uk
09-Dec-2002 10:41
[]= 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 )

<Строковые операторыОператор проверки принадлежности к классу>
 Last updated: Tue, 15 Nov 2005