PHP Array tutorial - Associative arrays

Home - Tutorials - Basics

In this tutorial I will show you how to work with arrays in PHP. You will learn how to create, sort or print an array. Besides this we will touch on multidimensional arrays as well.

Tutorial info:

Name:PHP Array tutorial
Total steps:7

Bookmark PHP Array tutorial

Step 4 - Associative arrays

PHP Array tutorial

In general PHP arrays are maps, which means that it is a type that maps values to keys. In our example it means that where the key is 0 there the value is "red" and where the key is 1 there the value is "green". However you have the possibility to use more meaningful keys. Associative array means that you can assign an arbitray key to every value. Associative arrays are sometimes referred to as dictionaries. Our colorList array can be defined as associative array like this:

  1. $colorList = array("apple"=>"red",
  2. "grass"=>"green",
  3. "sky"=>"blue",
  4. "night"=>"black",
  5. "wall"=>"white");
You have to remember that array keys are case-sensitive, but type insensitive. It means that 'a' differs from 'A' but '1' is the same as 1.
So, the array above can be defined (created) one-by-one elements like this:
  1. $colorList["apple"] = "red";
  2. $colorList["grass"] = "green";
  3. $colorList["sky"] = "blue";
  4. $colorList["night"] = "black";
  5. $colorList["wall"] = "white";
And you can display the content similar to the normal array, but here you need to use the string value instead of the number.
  1. echo "The sky is ".$colorList["sky"]
  2. ." and the grass is ".$colorList["grass"];
You can mix your array and use numbers and strings in the same list like this:
  1. $colorList["apple"] = "red";
  2. $colorList[5] = "green";
  3. $colorList["sky"] = "blue";
  4. $colorList["night"] = "black";
  5. $colorList[22] = "white";
As you can see even the numbers can be any so you don't have to make it continous. However be aware of using such mixed arrays as it can result errors.

In the next step we will discuss some usefull array functions.

Previous Step of PHP Array tutorialNext Step of PHP Array tutorial

Tags: array, php array, sort array, create array, print array, array length

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.138