📖 Scenario: You are creating a small contact list for your friends. Each friend has a name and a phone number.
🎯 Goal: Build an associative array in PHP that stores friends' names as keys and their phone numbers as values.
📋 What You'll Learn
Create an associative array called contacts with exact key-value pairs
Add a variable called new_contact set to 'Bob'
Use the array_key_exists function to check if a contact exists
Print the phone number of the new_contact if it exists
💡 Why This Matters
🌍 Real World
Associative arrays are used to store data with named keys, like contact lists, settings, or user profiles.
💼 Career
Knowing how to create and use associative arrays is essential for backend web development and data handling in PHP.
Progress0 / 4 steps
1
Create the contacts associative array
Create an associative array called contacts with these exact entries: 'Alice' => '123-4567', 'Bob' => '234-5678', and 'Charlie' => '345-6789'.
PHP
Hint
Use square brackets [] to create the array and separate key-value pairs with =>.
2
Add a new_contact variable
Add a variable called new_contact and set it to the string 'Bob'.
PHP
Hint
Use = to assign the string 'Bob' to the variable new_contact.
3
Check if new_contact exists in contacts
Use an if statement with array_key_exists to check if new_contact is a key in contacts. Inside the if, assign the phone number to a variable called phone_number.
PHP
Hint
Use array_key_exists($new_contact, $contacts) inside the if condition.
4
Print the phone number
Print the value of phone_number using echo.
PHP
Hint
Use echo $phone_number; to display the phone number.
Practice
(1/5)
1. Which of the following is the correct way to create an associative array in PHP with keys "name" and "age"?
easy
A. $person = ("name" => "Alice", "age" => 30);
B. $person = {"name": "Alice", "age": 30};
C. $person = array("Alice", 30);
D. $person = ["name" => "Alice", "age" => 30];
Solution
Step 1: Understand PHP associative array syntax
Associative arrays use square brackets with key => value pairs.
Step 2: Identify correct syntax among options
$person = ["name" => "Alice", "age" => 30]; uses square brackets and => correctly; others use invalid syntax.
Using = instead of => for key-value pair -> Option C
Quick Check:
Use => for key-value pairs [OK]
Hint: Use =>, not =, between key and value [OK]
Common Mistakes:
Using single = instead of =>
Omitting commas between pairs
Not quoting string keys
5. You want to create an associative array in PHP that maps product names to their prices, but only include products with a price greater than 20. Which code correctly creates this filtered associative array?