PHP Conference Fukuoka 2025

ArrayObject::exchangeArray

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

ArrayObject::exchangeArraySustituye un array por otro

Descripción

public ArrayObject::exchangeArray(array|object $array): array

Sustituye el array actual por otro array o un objeto.

Parámetros

array

El nuevo array o objeto a utilizar.

Valores devueltos

Devuelve el antiguo array.

Ejemplos

Ejemplo #1 Ejemplo con ArrayObject::exchangeArray()

<?php
// Arrays de frutas
$fruits = array("limones" => 1, "naranjas" => 4, "plátanos" => 5, "manzanas" => 10);
// Array de ciudades en Europa
$locations = array('Ámsterdam', 'París', 'Londres');

$fruitsArrayObject = new ArrayObject($fruits);

// Intercambio de frutas por ciudades
$old = $fruitsArrayObject->exchangeArray($locations);
var_dump($old);
var_dump($fruitsArrayObject);

?>

El ejemplo anterior mostrará :

array(4) {
  ["limones"]=>
  int(1)
  ["naranjas"]=>
  int(4)
  ["plátanos"]=>
  int(5)
  ["manzanas"]=>
  int(10)
}
object(ArrayObject)#1 (1) {
  ["storage":"ArrayObject":private]=>
  array(3) {
    [0]=>
    string(9) "Ámsterdam"
    [1]=>
    string(5) "París"
    [2]=>
    string(7) "Londres"
  }
}

add a note

User Contributed Notes 1 note

up
4
Corentin Larose
11 years ago
It's worth notting that ArrayObject::exchangeArray() doesn't call ArrayObject::offsetSet() internally for each offset/property of the array/object provided in argument.It's also worth noting the let's say "unexpected" behavior of get/set:<?phpclass MyArrayObject extends ArrayObject{    public function offsetSet($name, $value)    {        parent::offsetSet($name . '_control', $value);        parent::offsetSet($name, $value);    }}$test = new MyArrayObject();$test->setFlags(\ArrayObject::ARRAY_AS_PROPS);$test['my_value_1'] = 1;$test['my_value_1'] = $test['my_value_1'] + 1;$test['my_value_1'] += 1;$test['my_value_1'] ++;++ $test['my_value_1'];$test->my_value_2 = 1;$test->my_value_2 = $test->my_value_2 + 1;$test->my_value_2 += 1;$test->my_value_2 ++;++ $test->my_value_2;print_r($test);// Prints out:MyArrayObject Object(    [storage:ArrayObject:private] => Array        (            [my_value_1_control] => 3            [my_value_1] => 5            [my_value_2_control] => 2            [my_value_2] => 5        ))?>
To Top