fork(2) download
  1. <?php
  2.  
  3. $o1 = new stdClass;
  4. $a = 'd';
  5. //This is the base array or the initial structure
  6. $o1->ar1 = ['a', 'b', ['ca', 'cb']];
  7. $o1->ar1[3] = & $a; //set 3rd offset to reference $a
  8.  
  9. //direct copy (not passed by reference)
  10. $o1->ar2 = $o1->ar1; //alternatively array_replace($o1->ar1, []);
  11. $o1->ar1[0] = 'z'; //set offset 0 of ar1 = z do not change ar2
  12. $o1->ar1[3] = 'e'; //$a = e (changes value of 3rd offset to e in ar1 and ar2)
  13.  
  14. //copy and remove reference to 3rd offset of ar1 and change 2nd offset to a new array
  15. $o1->ar3 = array_replace($o1->ar1, [2 => ['aa'], 3 => 'd']);
  16.  
  17. //maintain original array of the 2nd offset in ar1 and change the value at offset 0
  18. //also remove reference of the 2nd offset
  19. //note: offset 3 and 2 are transposed
  20. $o1->ar4 = array_replace_recursive($o1->ar1, [3 => 'f', 2 => ['bb']]);
  21.  
  22. var_dump($o1);
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
object(stdClass)#1 (4) {
  ["ar1"]=>
  array(4) {
    [0]=>
    string(1) "z"
    [1]=>
    string(1) "b"
    [2]=>
    array(2) {
      [0]=>
      string(2) "ca"
      [1]=>
      string(2) "cb"
    }
    [3]=>
    &string(1) "e"
  }
  ["ar2"]=>
  array(4) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    array(2) {
      [0]=>
      string(2) "ca"
      [1]=>
      string(2) "cb"
    }
    [3]=>
    &string(1) "e"
  }
  ["ar3"]=>
  array(4) {
    [0]=>
    string(1) "z"
    [1]=>
    string(1) "b"
    [2]=>
    array(1) {
      [0]=>
      string(2) "aa"
    }
    [3]=>
    string(1) "d"
  }
  ["ar4"]=>
  array(4) {
    [0]=>
    string(1) "z"
    [1]=>
    string(1) "b"
    [2]=>
    array(2) {
      [0]=>
      string(2) "bb"
      [1]=>
      string(2) "cb"
    }
    [3]=>
    string(1) "f"
  }
}