Example 1 — Replace a Value by Key
Change the item at index 1 of a list.
<?php
$letters = ["a", "b", "c"];
$result = array_replace($letters, [1 => "B"]);
echo implode(", ", $result), PHP_EOL; How It Works
- Create the base list. It holds a, b and c.
- Prepare a replacement. Key
1has the new valueB. - Call array_replace(). Index 1 is replaced and the others stay.
- Print the result. The original
$lettersis unchanged.

