Monday, 20 January 2014
Labels:
Php
,
Tutorial
A complete PHP Tutorial For Beginners To Learn PHP Basic Part 3
Posted by
Unknown
at
01:18
PHP Arrays
What is an Array?
- A variable is a storage area holding a number or text.
- An array is a special variable, which can store multiple values in one single variable. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
- $cars1="Saab";
- $cars2="Volvo";
- $cars3="BMW";
- In PHP, there are three kind of arrays:
- Numeric array - An array with a numeric index
- 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 array element with a numeric index. There are two methods to create a numeric array.
- 1. In the following example the index are automatically assigned (the index starts at 0):
- $cars=array("Saab","Volvo","BMW","Toyota");
- 2. In the following example we assign the index manually:
- $cars[0]="Saab";
- $cars[1]="Volvo";
- $cars[2]="BMW";
- $cars[3]="Toyota";
Example
- In the following example you access the variable values by referring to the array name and index:
- <?php
- $cars[0]="Saab";
- $cars[1]="Volvo";
- $cars[2]="BMW";
- $cars[3]="Toyota";
- echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";
- ?>
- The code above will output: "Saab and Volvo are Swedish cars."
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. With associative arrays we can use the values as keys and assign values to them.
- $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 1
- The code above will output: "Peter is 32 years old."
- <?php
- $ages['Peter'] = "32";
- $ages['Quagmire'] = "30";
- $ages['Joe'] = "34";
- echo "Peter is " .
- $ages['Peter'] . " 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 1
- $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
- )
- )
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment