This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
You can assign your own keys to array elements -- and they don't have to be numbers. In fact, your code can be easier to read and understand if you use a name for a key. This is called an Associative Array, because a specific key is associated with a specific value.
Arrays are also referred to as a hash or dictionary
Comma After Elements
The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end.
Extract
You can use the extract function to extract the key value pairs as individual variables.
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array);
Gives us the variables $color = "blue", $size = "medium", and $shape = "sphere".
Example
You can even use spaces to line up the values.
$iceCream = array(
'Alena' => 'Black Cherry',
'Dave' => 'Cookies and Cream',
'Treasure' => 'Chocolate',
'Rialla' => 'Strawberry'
);
Shortcut for assigning values
$iceCream = [
'Alena' => 'Black Cherry',
'Dave' => 'Cookies and Cream',
'Treasure' => 'Chocolate',
'Rialla' => 'Strawberry'
];
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up