Monday 20 January 2014

A complete PHP Tutorial For Beginners To Learn PHP Basic Part 3

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:
    1. $cars1="Saab"; 
    2. $cars2="Volvo"; 
    3. $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:
    1. <?php 
    2. $cars[0]="Saab"; 
    3. $cars[1]="Volvo"; 
    4. $cars[2]="BMW"; 
    5. $cars[3]="Toyota";
    6. echo $cars[0] . " and " . $cars[1] . " are Swedish cars."; 
    7. ?>
  • 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.
    1. $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

  • Example 1

    • The code above will output: "Peter is 32 years old."
    1. <?php 
    2. $ages['Peter'] = "32"; 
    3. $ages['Quagmire'] = "30"; 
    4. $ages['Joe'] = "34"; 
    5. echo "Peter is " . 
    6. $ages['Peter'] . " years old."; 
    7. ?>
  • 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

    1. $families = array 
    2. "Griffin"=>array 
    3. "Peter", "Lois", "Megan" 
    4. ),
    5.  "Quagmire"=>array 
    6. "Glenn" 
    7. ),
    8. "Brown"=>array 
    9. "Cleveland", "Loretta", "Junior" 
    10. );
  • The array above would look like this if written to the output:

  1. Array 
  2. [Griffin] => Array 
  3. [0] => Peter 
  4. [1] => Lois 
  5. [2] => Megan 
  6. [Quagmire] => Array 
  7. [0] => Glenn 
  8. [Brown] => Array 
  9. [0] => Cleveland 
  10. [1] => Loretta 
  11. [2] => Junior 
  12. )

No comments :

Post a Comment