The value of the expression is compared with the values for each case in the structure

If there is a match, the code associated with that case is executed

After a code is executed, break is used to stop the code from running into the next case

The default statement is used if none of the cases are true

<html>

<body>

<?php

switch ($x)

{

case 1:

echo "Number 1";

break;

case 2:

echo "Number 2";

break;

case 3:

echo "Number 3";

break;

default:

echo "No number between 1 and 3";

}

?>

</body>

</html> What is an array?

When working with PHP, sooner or later, you might want to create many similar variables.

Instead of having many similar variables, you can store the data as elements in an array.

Each element in the array has its own ID so that it can be easily accessed.

There are three different kind of arrays:

Numeric array - An array with a numeric ID key

Associative array - An array where each ID key is associated with a value

Multidimensional array - An array containing one or more arrays

Numeric Arrays

A numeric array stores each element with a numeric ID key.

There are different ways to create a numeric array.

Example 1

In this example the ID key is automatically assigned:

$names = array("Peter","Quagmire","Joe"); Example 2

In this example we assign the ID key manually:

$names[0] = "Peter";

$names[1] = "Quagmire";

$names[2] = "Joe"; The ID keys can be used in a script:

<?php

$names[0] = "Peter";

$names[1] = "Quagmire";

$names[2] = "Joe";

echo $names[1] . " and " . $names[2] .

" are ". $names[0] . "'s neighbors";

?> The code above will output:

Quagmire and Joe are Peter's neighbors

Associative Arrays

An associative array, each ID key is associated with a value.

When storing data about specific named values, a numerical array is not always the best way to do it.

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