How can selective replacement of array elements be achieved in PHP classes without overwriting the entire variable?

When working with PHP classes and arrays, selectively replacing elements without overwriting the entire variable can be achieved by using array functions like array_replace() or array_merge(). These functions allow you to merge arrays while selectively replacing elements based on keys.

class Example {
    private $data = [];

    public function __construct($initialData) {
        $this->data = $initialData;
    }

    public function replaceElement($key, $value) {
        $this->data = array_replace($this->data, [$key => $value]);
    }

    public function getData() {
        return $this->data;
    }
}

// Example of how to use the class
$initialData = ['a' => 1, 'b' => 2, 'c' => 3];
$example = new Example($initialData);

$example->replaceElement('b', 5);

print_r($example->getData());