Logo
Unit 8 – Associative Arrays

Associative Arrays

Duration: 5 minutes

Stepping further into the realm of PHP arrays, we encounter the “Associative Arrays”. Unlike indexed arrays which use numbers as indices, associative arrays employ named keys. This characteristic makes associative arrays incredibly potent for tasks where you need to associate values with specific names or labels.

In this module, we’ll focus on defining and effectively using associative arrays. Let’s embark on this elucidative journey!

Basics of Associative Arrays

Associative arrays are arrays that use named keys to store values. These keys can be any string, making it easier to remember and access values compared to numeric indices.

Creating Associative Arrays

Associative arrays can be created using the array() function or the short array syntax.

Here’s how:

// Using the array() function
$student = array("firstName" => "Zahwah", "major" => "Information Technology");
// Using the short array syntax
$colors = ["sky" => "blue", "grass" => "green", "apple" => "red"];

Accessing and Modifying Associative Arrays

Values in associative arrays are accessed using their named keys:

echo $student["firstName"]; // Outputs: Zahwah

To modify a value, assign a new value to its key:

$student["firstName"] = "Aisha"; // Changes the value of the key "firstName" to Aisha

It’s also straightforward to add new key-value pairs:

$student["hobby"] = "painting"; // Adds a new key "hobby" with value "painting"

Exercise

Time to apply what you’ve learned!

  • Create an associative array detailing a book, with keys like “title”, “author”, and “publicationYear”.
  • Display the title of the book.
  • Modify the author’s name.
  • Add a new key-value pair, “genre”, to the book details.

Conclusion

You’ve successfully deepened your understanding of associative arrays in PHP. These arrays are invaluable when representing data that has a clear name or label associated with it.

By mastering associative arrays, you’re enhancing your data structuring capabilities in PHP.

Next Tutorial: String Manipulation

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!