Programming Languages PHP Subjective
Sep 23, 2025

What is the output of this PHP code? Explain reference behavior and memory management.

Detailed Explanation

Code Analysis:

$a = ["x" => 1, "y" => 2];
$b = &$a;
$c = $a;

$a["x"] = 10;
$c["y"] = 20;

unset($a);

var_dump($b);
var_dump($c);

Output:

array(2) {
  ["x"]=> int(10)
  ["y"]=> int(2)
}
array(2) {
  ["x"]=> int(1)
  ["y"]=> int(20)
}

Explanation:

  1. $b = &$a: $b becomes a reference to $a (same memory location)
  2. $c = $a: $c gets a copy of $a (copy-on-write)
  3. $a["x"] = 10: Modifies original array, affects both $a and $b
  4. $c["y"] = 20: Triggers copy-on-write, $c becomes independent
  5. unset($a): Removes $a variable, but $b still references the data

Memory Management:

  • Copy-on-Write: PHP optimizes memory by sharing data until modification
  • Reference Counting: Memory freed when all references are removed
  • Zval Structure: Each variable has reference count and type information

Best Practices:

  • Use references sparingly to avoid confusion
  • Understand copy-on-write behavior for large arrays
  • Use unset() to free memory when working with large datasets
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback