How to set a value with a specific key
$name = array('first' => 'Ray', 'last' => 'Harris');
$name['middle'] = 'Thomas';
What happens when you omit the key when adding a value
$name = array('first' => 'Ray', 'last' => 'Harris');
$name[] = 'Thomas'; // key is 0
How to get a value at a specified key
$name = array('first' => 'Ray', 'last' => 'Harris');
$first_name = $name['first'];
$last_name = $name['last'];
How to delete values from an array
$name = array('first' => 'Ray', 'last' => 'Harris');
unset($name['first']); // delete the value from an element
unset($name); // delete all elements
How to use variable substitution with array elements
$name = array('first' => 'Ray', 'last' => 'Harris');
echo("First Name: " . $name['first'] . "<br />\n"); // First Name: Ray
echo("First Name: " . $name[first] . "<br />\n"); // Generates a parse error
echo("First Name: {$name['first']}"); // First Name: Ray
'Ray', 'last' => 'Harris');
echo("First Name: " . $name['first'] . "
\n"); // First Name: Ray
echo("First Name: " . $name[first] . "
\n"); // Generates a parse error
echo("First Name: {$name['first']}"); // First Name: Ray
?>
- To set or get a value in an associative array, specify the key for the value within the brackets.
- If you use an empty pair of brackets to add an element to an array, PHP uses an integer key for the element, which usually isn’t what you want for an associative array.
- You can access array elements using variable substitution in a double-quoted string. To do that for a string key, you don’t need to code quotes around the key. However, if you place braces around the element to separate it from other text in the string, you must include quotes around the key.
Back