0
0
PHPprogramming~5 mins

Associative array creation in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an associative array in PHP?
An associative array in PHP is a collection of key-value pairs where each key is a unique string or integer used to access its corresponding value.
Click to reveal answer
beginner
How do you create an associative array with keys 'name' and 'age' in PHP?
You create it like this:<br>$person = ['name' => 'Alice', 'age' => 30];<br>This means 'name' points to 'Alice' and 'age' points to 30.
Click to reveal answer
intermediate
What happens if you use the same key twice in an associative array?
The last value assigned to that key will overwrite any previous value. Keys must be unique in an associative array.
Click to reveal answer
beginner
How can you access the value of the key 'age' in an associative array named $person?
Use the syntax: $person['age']; This will give you the value stored under the key 'age'.
Click to reveal answer
beginner
Can keys in PHP associative arrays be integers?
Yes, keys can be integers or strings. PHP treats integer keys as normal keys in associative arrays.
Click to reveal answer
Which of the following is the correct way to create an associative array in PHP?
A$arr = array('red', 'large');
B$arr = ('color', 'red', 'size', 'large');
C$arr = ['red', 'large'];
D$arr = ['color' => 'red', 'size' => 'large'];
What will be the output of echo $arr['name']; if $arr = ['name' => 'Bob'];?
ABob
Bname
CError
DArray
If you create $arr = ['key' => 'first', 'key' => 'second'];, what is the value of $arr['key']?
Afirst
Bsecond
CArray
DError
Which data types can be used as keys in PHP associative arrays?
AOnly strings
BOnly integers
CStrings and integers
DAny data type
How do you add a new key-value pair 'city' => 'Paris' to an existing associative array $arr?
A$arr['city'] = 'Paris';
B$arr->city = 'Paris';
Carray_push($arr, 'city' => 'Paris');
D$arr.add('city', 'Paris');
Explain how to create and access values in an associative array in PHP.
Think about how you label things with names and then find them by those names.
You got /3 concepts.
    Describe what happens if you use duplicate keys when creating an associative array.
    Imagine writing a label twice on the same box.
    You got /3 concepts.