Arrays hold many values in one place. Accessing and changing these values helps you work with data easily.
0
0
Array access and modification in PHP
Introduction
You want to get a specific item from a list of names.
You need to update a score in a list of game scores.
You want to add a new item to a shopping list.
You want to remove or change an item in a list of tasks.
Syntax
PHP
<?php // Define an array $array = ["apple", "banana", "cherry"]; // Access an element by index $value = $array[1]; // Modify an element by index $array[1] = "blueberry"; ?>
Array indexes start at 0, so $array[0] is the first item.
You can change the value by assigning a new value to the index.
Examples
Prints 10, the first item in the array.
PHP
<?php // Access first element $array = [10, 20, 30]; echo $array[0]; ?>
Changes "blue" to "yellow" and prints it.
PHP
<?php // Modify last element $array = ["red", "green", "blue"]; $array[2] = "yellow"; echo $array[2]; ?>
Trying to access an element in an empty array causes an error.
PHP
<?php // Access empty array $array = []; // echo $array[0]; // This will cause an error because the array is empty ?>
Changes the only element from 100 to 200 and prints it.
PHP
<?php // Modify single element array $array = [100]; $array[0] = 200; echo $array[0]; ?>
Sample Program
This program shows how to access and change an item in an array. It prints the array before and after the change.
PHP
<?php // Create an array of fruits $fruits = ["apple", "banana", "cherry"]; // Print original array echo "Original array:\n"; print_r($fruits); // Access the second fruit $second_fruit = $fruits[1]; echo "\nSecond fruit: $second_fruit\n"; // Modify the second fruit $fruits[1] = "blueberry"; echo "\nModified array:\n"; print_r($fruits); ?>
OutputSuccess
Important Notes
Accessing or modifying an element by index is very fast, usually O(1) time.
Be careful not to access an index that does not exist; it causes errors or warnings.
Use modification when you want to update a value; use array functions if you want to add or remove elements.
Summary
Arrays store multiple values accessible by index starting at 0.
You can get or change values by using the index inside square brackets.
Always check the array size before accessing to avoid errors.