Hello World Master

Tutorials, articles and quizzes on Software Development

PHP > Articles

Associative Arrays in PHP

We can create Associative Arrays to represent a collection of data in PHP. Note that this is different from Numerical Arrays, which store a list of data in a specific order.

Data in objects have their own names and values. Let’s do an example where we want to create a duck and define different information about that duck.

<?php
  $duck = array(
    "name" => "Sylvester",
    "feather_color" => "white",
  );
?>

Here we’re saying that our duck’s name is Sylvester and that the duck’s feathers are white.

We can print our different attributes to the screen like this

<?php
  $duck = array(
    "name" => "Sylvester",
    "feather_color" => "white",
  );
   echo $duck["name"];
?>

Which will print out “Sylvester” and

<?php
  $duck = array(
    "name" => "Sylvester",
    "feather_color" => "white",
  );
   echo $duck["feather_color"];
?>

Which will print out “white”

What if you want one of the attributes in our associative array? Lets change our Ducks name to Mittens

<?php
  duck["name"] = "Mittens"
?>

We could also use bracket notation to update our attribute

<?php
  duck["name"] = "Mittens";
?>