PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Opérateurs de types> <Opérateurs de chaînes
Last updated: Fri, 10 Oct 2008

view this page in

Opérateurs de tableaux

Opérateurs de tableaux
Exemple Nom Résultat
$a + $b Union Union de $a et $b.
$a == $b Egalité TRUE si $a et $b contiennent les mêmes paires clés/valeurs.
$a === $b Identique TRUE si $a et $b contiennent les mêmes paires clés/valeurs dans le même ordre et du même type.
$a != $b Inégalité TRUE si $a n'est pas égal à $b.
$a <> $b Inégalité TRUE si $a n'est pas égal à $b.
$a !== $b Non-identique TRUE si $a n'est pas identique à $b.

L'opérateur + ajoute les éléments du tableau de droite au tableau de gauche, sans pour autant écrasées les clés communes.

<?php
$a 
= array("a" => "pomme""b" => "banane");
$b = array("a" =>"poire""b" => "fraise""c" => "cerise");

$c $a $b// Union de $a et $b
echo "Union de \$a et \$b : \n";
var_dump($c);

$c $b $a// Union de $b et $a
echo "Union de \$b et \$a : \n";
var_dump($c);
?>
À l'exécution, le script affichera :
Union de $a et $b :
array(3) {
  ["a"]=>
  string(5) "pomme"
  ["b"]=>
  string(6) "banane"
  ["c"]=>
  string(6) "cerise"
}
Union de $b et $a :
array(3) {
  ["a"]=>
  string(5) "poire"
  ["b"]=>
  string(6) "fraise"
  ["c"]=>
  string(6) "cerise"
}

Les éléments d'un tableau sont égaux en terme de comparaison s'ils ont la même clé et la même valeur.

Exemple #1 Comparer des tableaux

<?php
$a 
= array("pomme""banane");
$b = array(=> "banane""0" => "pomme");

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

Voyez aussi le manuel aux sections Tableaux et fonctions de tableaux.



Opérateurs de types> <Opérateurs de chaînes
Last updated: Fri, 10 Oct 2008
 
add a note add a note User Contributed Notes
Opérateurs de tableaux
csaba at alum dot mit dot edu
24-Jun-2008 09:54
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
csaba at alum dot mit dot edu
13-Dec-2007 02:42
Simple array arithmetic:
If you want to add or subtract the elements at identical keys...

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

function
array_subtract($a1, $a2) {  // ...
  // subtracts the values at identical keys from the corresponding value in $a1
 
$aRes = $a1;
 
$aRays = func_get_args();
  for (
$i=1;$i<sizeof($aRays);++$i) {
   
$aRay = $aRays[$i];
    foreach (
$aRay as $key => $val) {
      if (
array_key_exists($key, $aRes)) $aRes[$key] -= $aRay[$key];
      else
$aRes[$key] = -$aRay[$key]; } }
  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 the first += only in array_add() to .=
Csaba Gabor from Vienna
Q1712 at online dot ms
20-Apr-2007 06:54
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)
?>
puneet singh @ value-one dot com
18-Jan-2006 11: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 10: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 09:44
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.
Peter
29-Oct-2004 08: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 02: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 07: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 11: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 )

Opérateurs de types> <Opérateurs de chaînes
Last updated: Fri, 10 Oct 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites