PHP Arrays Tutorials

In PHP an array is a collection of variables that do not have to be off the same type (This is known as PHP Type Juggling).  Arrays in PHP are very important and are used quiet often.
The easiest way to explain what an array in PHP is to show you how to define an array using examples so lets look at how we declare a regular variable

In php Variables store values like

<?php
$myWebsiteName = “beginner-tutorials.com“;
?>

In PHP an array stores a set of values

<?php
$myWebsiteName_array = (“beginner-tutorials.com“, “Elearningtutor.com“, “yahoo.com“);
?>

So, how do you assign values to arrays, this is handled by specifying which element of the array you wish to work with. For Example (0,1,2 are our key identifiers for our array), this is known as a numerical indexed array.

<?php

$myWebsiteName_array [0] = “beginner-tutorials.com”;  
$myWebsiteName_array [1] = “Elearningtutor.com“;
$myWebsiteName _array [2] = “yahoo.com”; ?>

One important thing to note is that, by default, php arrays start numbering their elements at zero.

Displaying the Contents of our array.

Displaying the contents of our array using a for loop is quiet easy.
Example.


For ($i = 0; i < myWebsiteName _array.length(); i++){
Echo “Array Element “ + i + “ = ” + myWebsiteName _array.length[i];
}


Our if we simply wanted to display an item in position 2 of our array we would use the following code


Echo “Array 2 ” + myWebsiteName _array.[1];

Associative Arrays and Multidimensional Arrays

In an associative array a key is associated with a value


Here's a quick example of what that means:


$books["John"] = ‘A winters tale’;
echo "John likes to read  - $" . $books["John"] . "<br />";


The output is John likes to read A winters tale


An Array does not have to be a simple list of keys and values; each array element can contain another array as a value, which in turn can hold other arrays as well. In such a way you can create two-dimensional or three-dimensional array.


Lets have a look at example, where we have an array of films broken down into an array category of Comedy, Cartoon and Westerns containing the names of the films.


$films = array
  (
 "Comedy"=>array
  (
  "My Best Friends Wedding",
  "SuperBad",
  ),
  "Cartoon"=>array
  (
 "Popeye"
 "Simpsons"
 ),
  "Western"=>array
  (
  "The good bad and the ugly",
  "OK Coral",

  )

Thats It.

php tutorials