With associative arrays we can use the values as keys and assign values to them.

Example 1

In this example we use an array to assign ages to the different persons:

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Example 2

This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = "32";

$ages['Quagmire'] = "30";

$ages['Joe'] = "34"; The ID keys can be used in a script:

<?php

$ages['Peter'] = "32";

$ages['Quagmire'] = "30";

$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";

?> The code above will output:

Peter is 32 years old.

Multidimensional Arrays

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array

"Griffin"=>array

"Peter",

"Lois",

"Megan"

),

"Quagmire"=>array

"Glenn"

),

"Brown"=>array

"Cleveland",

"Loretta",

"Junior"

); The array above would look like this if written to the output:

Array

[Griffin] => Array

[0] => Peter

[1] => Lois

[2] => Megan

[Quagmire] => Array

[0] => Glenn

[Brown] => Array

[0] => Cleveland

[1] => Loretta

[2] => Junior

) Example 2

Lets try displaying a single value from the array above:

echo "Is " . $families['Griffin'][2] .

" a part of the Griffin family?"; The code above will output:

Is Megan a part of the Griffin family? Looping

Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this.

In PHP we have the following looping statements:

while - loops through a block of code if and as long as a specified condition is true

You've reached the end of published parts.

⏰ Last updated: Jan 14, 2010 ⏰

Add this story to your Library to get notified about new parts!

PHP-languageWhere stories live. Discover now