arrays

Document Sample
arrays Powered By Docstoc
					   PHP

Using Arrays
               Arrays
• What is an ‘Array’?
• An Array is a data structure which allows you
  to store numbered pieces of data for easy
  access.
• Think of an Array as a group of variables
  which use the same name and are accessed by
  a numbered value.
• An egg carton could be a visual example of an
  Array.
                 Arrays
• In PHP Arrays are objects that are capable of
  storing a sequence of values. These values are
  stored in indexed locations within the array.
• Objects are entities that exist to model real
  world things.
• An Object consists of two things:
  • Properties
  • Methods
                         Arrays
Each variable location in an array is called an
                                                  Index   City Name
   Element.                                       0       New York
Each Element is referenced by an index
                                                  1       Dallas
   number. The index number must be a non-
   negative integer.                              2       St. Louis

Index numbers in an array begin at ‘0’.           3       Houston

I.e.. Array’s are ‘zero based’                    4       Oklahoma City
The length or size of an array is the number
   of elements contained in the array.
Because arrays start with ‘0’ the length is the
   value of the last index + 1.
Use square brackets to reference the index
   number [0].
                      Arrays
A array is created or initialized using the array   Inde   City Name
                                                    x
   keyword with the array() constructor.            0      New York

Syntax:                                             1      Dallas

array name = array(elem0, elem1,elem2, elem         2      St. Louis

   n);                                              3      Houston

An array must be declared before it can be          4      Oklahoma
                                                           City
   accessed.
    Declaring and Initializing
        Indexed Arrays
• An element refers to each piece of data that is
  stored within an array
  • By default, it starts with the number zero (0)
• An index is an element’s numeric position
  within the array
  • Referenced by enclosing its index in brackets at
    the end of the array name:
    $Provinces[1]
         Creating an Array
• The array() construct syntax is:
    $array_name = array(values);
    $Provinces = array(
         "Newfoundland and Labrador",
         "Prince Edward Island",
         "Nova Scotia",
         "New Brunswick",
         "Quebec",
         "Ontario",
         "Manitoba",
         "Saskatchewan",
         "Alberta",
         "British Columbia"
         );
 Creating an Array (continued)
• Array name and brackets syntax is:
    $array_name[ ]
    $Provinces[]   =   "Newfoundland and Labrador";
    $Provinces[]   =   "Prince Edward Island";
    $Provinces[]   =   "Nova Scotia";
    $Provinces[]   =   "New Brunswick";
    $Provinces[]   =   "Quebec";
    $Provinces[]   =   "Ontario";
    $Provinces[]   =   "Manitoba";
    $Provinces[]   =   "Saskatchewan";
    $Provinces[]   =   "Alberta";
    $Provinces[]   =   "British Columbia";
                   Arrays
Consider the following       Index   City Name
  table:
                             0       New York
To store these variables
  we could assign the        1       Dallas
  values to 5 variables.
Or create an array to hold   2       St. Louis
  all the values at once.
                             3       Houston

                             4       Oklahoma
                                     City
                      Arrays
Declaring the array:                                     City Name
                                                 Index
 $city = array[] = “New Orleans”
                                                 0       New York
(The index is automatically set to 0)
$city[0] = ‘New York’;
                                                 1       Dallas



$city[1] = ‘Dallas’;                             2       St. Louis



$city[2] = ‘St. Louis’;
                                                 3       Houston



$city[3] = ‘Houston’;
                                                 4       Oklahoma
                                                         City


$city[4] = ‘Oklahoma City’;
The length property is set to the value in the
  parentheses.
                     Arrays
OR                                                    City Name
                                              Index

Declaring the array:
                                              0       New York

$city = array(‘New York’,’Dallas’,            1       Dallas

‘St. Louis’, ‘Houston’, ‘Oklahoma City’);     2       St. Louis

The length property is set to the number of   3       Houston

  arguments passed to the constructor.        4       Oklahoma
                                                      City
Arrays
 • Name the array using PHP
   naming conventions. Begins
   with a $ and letter or
   underscore.
 • The array object begins
   numbering the elements at ‘0’.
                  Arrays
Assign the value of an array element to a variable.
$city[0] = ‘New York’;
$bigtown = city[0];
$bigtown now has the value of ‘New York’.
Accessing Element Information
echo "<p>Canada's smallest province is $Provinces[1].<br
  />";
echo "Canada's largest province is $Provinces[4].</p>";




Figure 3-8 Output of elements in the $Provinces[ ] array
         count() Function
• Use the count() function to find the total
  number of elements in an array

  $Provinces = array("Newfoundland and Labrador", "Prince
  Edward
  Island", "Nova Scotia", "New Brunswick", "Quebec",
  "Ontario", " Manitoba", "Saskatchewan", "Alberta",
  "British Columbia");
  $Territories = array("Nunavut", "Northwest Territories",
  "Yukon
  Territory");
  echo "<p>Canada has ", count($Provinces), “ provinces
  and ",
       count($Territories), “ territories.</p>";
count() Function (continued)




    Figure 3-9 Output of the count() function
        print_r(),
     var_export(), and
    var_dump() Functions
• Use to print or return information about
  variables
• Most useful with arrays because they print the
  index and value of each element
         Modifying Elements
• Include the index for an individual element of the array:
  $HospitalDepts = array(
       "Anesthesia",                 // first element(0)
       "Molecular Biology",// second element
  (1)
       "Neurology");                 // third element
  (2)

  To change the first array element in the
  $HospitalDepts[] array from “Anesthesia” to
  “Anesthesiology” use:
  $HospitalDepts[0] = "Anesthesiology";
                  Arrays
Once an array has been populated you can extract the
  values very easily by using a loop.
We may know the array length, so a for loop will work
  nicely.
for($i = 0; $i < count($city); ++$i){
  echo $city[$i]. + “<br />”;
} $i also represents the value of the array index number.
          Associative Arrays
• What is an Associative Array?
• An Associative Array is a type of PHP array that uses
  a Name/Value pair to define an element in the array.
• Instead of an Index number to define an array
  element a String data type is used.
• A benefit is that if the array is sorted you do not have
  to worry about the rearranged index numbers.
• Remember Autoglobals are a type of Associative
  array.
  Declaring and Initializing
    Associative Arrays
• With associative arrays, you specify an
  element’s key by using the array operator (=>)
• The syntax for declaring and initializing an
  associative array is:
     $array_name = array(key=>value,
  ...);
Declaring and Initializing Associative
        Arrays (continued)
$Territories[100] = “Nunavut”;
$Territories[] = “Northwest Territories”;
$Territories[] = “Yukon Territory”;
print_r($Territories);
echo '<p>The $Territories array consists of ',
     count($Territories), “ elements.</p>”;
          Associative Arrays
• Assign the array values, like an indexed array except
  that in place of the index number you put a String
  value.
   • $story[ “color” ] = “green”;
   • $story[ “instrument” ] = “flugelhorn”;
   • $story[ “animal” ] = “wart hog”
   Echo “Little boy “. story[“color”] .”, come blow on your “.+
     story[“instrument”] . “! The “. story[“animal”]. “is in the
     corn. “
   Little boy green, come blow on your flugelhorn! The wart
     hog is in the corn.
       PHP

Using Array Functions
Adding and Removing Elements
from the Beginning of an Array
          (continued)




Figure 7-3 Output of an array modified with the array_shift()
           and array_unshift() functions
   Adding and Removing
Elements from the Beginning
        of an Array
• The array_shift() function removes the
  first element from the beginning of an array
  • Pass the name of the array whose first element you
    want to remove
• The array_unshift() function adds one
  or more elements to the beginning of an array
  • Pass the name of an array followed by comma-
    separated values for each element you want to add
Adding and Removing Elements
 from the Beginning of an Array
              (continued)
$TopGolfers = array(
     “Ernie Els”,
     “Phil Mickelson”,
     “Retief Goosen”,
     “Padraig Harrington”,
     “David Toms”,
     “Sergio Garcia”,
     “Adam Scott”,
     “Stewart Cink”);
array_shift($TopGolfers);
array_unshift($TopGolfers, “Tiger Woods”, “Vijay
  Singh”);
print_r($TopGolfers);
      array_splice()
          Function
• To add an element within an array, include a
  value of 0 as the third argument

$HospitalDepts = array(
      “Anesthesia”,           // first element (0)
      “Molecular Biology”,    // second element (1)
      “Neurology”,            // third element (2)
      “Pediatrics”);          // fourth element (3)
array_splice($HospitalDepts, 3, 0, “Ophthalmology”);
   Adding and Removing
Elements from the End of an
           Array
• The array_pop() function removes the last
  element from the end of an array
  • Pass the name of the array whose last
    element you want to remove
• The array_push() function adds one or
  more elements to the end of an array
  • Pass the name of an array followed by
    comma-separated values for each element
    you want to add
Adding and Removing Elements
     from the End of an Array
              (continued)
$HospitalDepts = array(
     “Anesthesia”,
     “Molecular Biology”,
     “Neurology”,
     “Pediatrics”);
array_pop($HospitalDepts);
array_push($HospitalDepts, “Psychiatry”, “Pulmonary
  Diseases”);
  Adding and Removing
 Elements Within an Array
• The array_splice() function adds or
  removes array elements
• The array_splice() function renumbers
  the indexes in the array
• The syntax for the array_splice()
  function is:
  array_splice(array_name, start,
    characters_to_delete, values_to_insert);
      array_splice()
      Function (continued)
• To add more than one element within an array,
  pass the array() construct as the fourth
  argument
• Separate the new element values by commas
  $HospitalDepts = array(
       “Anesthesia”,          // first element (0)
       “Molecular Biology”,   // second element (1)
       “Neurology”,           // third element (2)
       “Pediatrics”);         // fourth element (3)
  array_splice($HospitalDepts, 3, 0,
  array(“Ophthalmology”,
       “Otolaryngology”));
     array_splice()
     Function (continued)
• Delete array elements by omitting the fourth
  argument from the array_splice()
  function
  $HospitalDepts = array(
        “Anesthesia”,       // first element (0)
        “Molecular Biology”,     // second
    element (1)
        “Neurology”,        // third element (2)
        “Pediatrics”);      // fourth element
    (3)
  array_splice($HospitalDepts, 1, 2);
      unset() Function
• The unset() function removes array
  elements and other variables
• Pass to the unset() function the array name
  and index number of the element you want to
  remove
• To remove multiple elements, separate each
  index name and element number with commas
   unset($HospitalDepts[1],
 $HospitalDepts[2]);
      Removing Duplicate
          Elements
• The array_unique() function removes
  duplicate elements from an array
• Pass to the array_unique() function the
  name of the array from which you want to
  remove duplicate elements
• The array_values() and
  array_unique() functions do not operate
  directly on an array
• The array_unique() function does
  renumber the indexes after removing duplicate
  values in an array
    array_unique()Function
$TopGolfers = array(
     “Tiger Woods”, “Tiger Woods”, “Vijay Singh”, “Vijay
  Singh”,
     “Ernie Els”, “Phil Mickelson”, “Retief Goosen”,
     “Retief Goosen”, “Padraig Harrington”, “David Toms”,
     “Sergio Garcia”, “Adam Scott”, “Stewart Cink”);
echo “<p>The world's top golfers are:</p><p>”;

$TopGolfers = array_unique($TopGolfers);
$TopGolfers = array_values($TopGolfers);
for ($i=0; $i<count($TopGolfers); ++$i) {
     echo “{$TopGolfers[$i]}<br />”;
}
echo “</p>”;
    array_unique()Function
          (continued)




Figure 7-4 Output of an array after removing duplicate values
           with the array_unique() function
 Iterating Through an Array
• The internal array pointer refers to the
  currently selected element in an array
Table 7-1 Array pointer iteration functions
Iterating Through an Array
        (continued)




Figure 7-7 Output of an array without advancing the internal
array pointer

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:3
posted:1/29/2013
language:simple
pages:39