How to add an element to the end of an array
$letters = array('a', 'b', 'c', 'd'); // array is a, b, c, d
$letters[] = 'e';
How to set a value at a specific index
$letters = array('a', 'b', 'c', 'd'); // array is a, b, c, d
$letters[0] = 'e'; // array is e, b, c, d
$letters[3] = 'f'; // array is e, b, c, f
$letters[5] = 'g'; // array is e, b, c, f, NULL, g
How to get values from an array
$letters = array('a', 'b', 'c', 'd'); // array is a, b, c, d
$letter1 = $letters[0]; // $letter1 is 'a'
$letter2 = $letters[1]; // $letter2 is 'b'
$letter4 = $letters[4]; // $letter4 is NULL
How to delete values from an array
$letters = array('a', 'b', 'c', 'd'); // array is a, b, c, d
unset($letters[2]); // array is a, b, NULL, d
unset($letters); // $letters is NULL
How to remove elements that contain NULL values and reindex an array
$letters = array('a', 'b', 'c', 'd'); // array is a, b, c, d
unset($letters[2]); // array is a, b, NULL, d
$letters = array_values($letters); // array is a, b, d
How to use array elements with variable substitution
$name = array ('Ray', 'Harris');
echo("First Name: $name[0]") // First Name: Ray;
echo("First Name: {$name[0]}"); // First Name: Ray
- You can set and get elements from an array by coding the index for the element between brackets.
- When you add or delete elements from an array, you may leave gaps in the array that contain NULL values.
- You can access array elements using variable substitution in a double-quoted string. If necessary, you can place braces around the array name and index to separate the array element from the rest of the text in the string.
Back