How can PHP classes be used to store and manipulate arrays effectively?
PHP classes can be used to store and manipulate arrays effectively by creating a class that contains array properties and methods to manipulate those arrays. This allows for better organization of code, encapsulation of data, and reusability of array manipulation logic.
class ArrayManipulator {
private $array;
public function __construct($array) {
$this->array = $array;
}
public function addElement($element) {
$this->array[] = $element;
}
public function removeElement($index) {
unset($this->array[$index]);
}
public function getArray() {
return $this->array;
}
}
// Example usage
$array = [1, 2, 3];
$manipulator = new ArrayManipulator($array);
$manipulator->addElement(4);
$manipulator->removeElement(1);
print_r($manipulator->getArray());