Back to results for “Scope”
PHP › Arrays in PHP

How do you add, remove, and access elements within a PHP array?

Beginner

Answer

You can add an element to the end of an array using square bracket syntax or the array_push function, remove an element using unset for a specific key or array_pop to remove the last element, and access an element directly by referencing its index or key inside square brackets, giving you full control over the contents of an array as your program runs.
$colors = ['red', 'green'];
$colors[] = 'blue';
unset($colors[0]);
echo $colors[1];
Real-world example A task management application adds a new task to a list by appending it to an array, and removes a completed task by unsetting its specific key, keeping the array always reflecting the current active tasks.

Common follow-ups: What is the difference between unset and array_splice for removing elements?;How do you check if a specific key exists in an array?