PHP I : Arrays

Follow this lesson in Ullman Chapter 7. The scripts are located in the 07 directory.

 

The arrays you’re already using: $_GET and $_POST

These two arrays are two of the superglobals.

Older versions of PHP (before 4.1) use $HTTP_POST_VARS and $HTTP_GET_VARS instead.

Other superglobals include $_COOKIE, $_SESSION AND $_SERVER.

 

An Indexed Array
0 Fred
1 Barney
2 Wilma
3 Betty

 

A Keyed Array
hero Fred
hero_buddy Barney
hero_wife Wilma
buddy_wife Betty

 

Creating an Array

$flintstones = array(‘Fred’, ‘Barney’, ‘Wilma’, ‘Betty’);

$flintstones = array(1 => ‘Fred’, 2 => ‘Barney’, 3 => ‘Wilma’, 4 => ‘Betty’);

or

$flintstones = array(
1 => ‘Fred’,
2 => ‘Barney’,
3 => ‘Wilma’,
4 => ‘Betty’
);

or even

$flintstones = array(
1 => ‘Fred’,
‘Barney’,
‘Wilma’,
‘Betty’
);

Note that if you do not specify a starting index, your array is numbered starting with 0 !

 

$flintstones = array(‘hero’ => ‘Fred’, ‘hero_buddy’ => ‘Barney’, ‘hero_wife’ => ‘Wilma’, ‘buddy_wife’ => ‘Betty’);

or

$flintstones = array(
‘hero’ => ‘Fred’,
‘hero_buddy’ => ‘Barney’,
‘hero_wife’ => ‘Wilma’,
‘buddy_wife’ => ‘Betty’
);

 

Other Types of Arrays

Range:

$numbers = range(1, 10);

$letters = range(‘a’, ‘z’)

# You can use a third “step” parameter:

$even_numbers = range(0, 100, 2);

 

Printing an Array

You don’t always get what you expect.

print $flintstones;

gets you:

Array

While

print_r($flintstones);

gets you:

Array { [hero] => Fred [hero_buddy] => Barney [hero_wife] => Wilma [buddy_wife] => Betty }

Compare:

var_dump($flintstones);

 

Create a new PHP page with a form. The form should have at least four text boxes. It should allow the user to create an array, and it should print out that array as the result.

 

Adding to an Array

Add to an Indexed Array:

$flintstones[] = Pebbles;
$flintstones[] = Bam-Bam;
# if you specify no index, it’s added automatically

Add to a Keyed Array:

$flintstones[hero_daughter] = Pebbles;
$flintstones[buddy_son] = Bam-Bam;

 

Modifying an Array

$flintstones[6] = Boom-Boom;
# if you specify an existing index,
# the current value is modified

 

Deleting Items from an Array

unset($flintstones[6]);

or

unset($flintstones[‘buddy_son’]);

 

Clearing All Values from an Array

unset($flintstones);

or

$flintstones = array();

 

Counting the Elements of an Array

count($flintstones);

 

Accessing the Elements of an Array

print “The protagonist of The Flintstones is {$flintstones[‘hero’]}“;

or

print “The protagonist of The Flintstones is {$flintstones[‘1’]}“;

Note the all-important Curly Braces!

 

foreach ($array as $key => $value) {
   print “Key is $key. \n Value is $value.”;
}

 

foreach ($flintstones as $key => $value) {
   print “Key is $key. \n Value is $value.”;
}

 

Multidimensional Arrays: Arrays of Arrays

// Create the first array.
$veggies = array (1 => ‘lettuce’, ‘broccoli’, ‘carrots’, ‘turnips’);

// Create the second array.
$meats = array (1 => ‘beef’, ‘fish’, ‘pork’, ‘mystery’);

// Create the third array.
$dairy = array (1 => ‘milk’, ‘cream’, ‘butter’, ‘eggs’);

// Create the multidimensional array.
$food = array (
‘veg’ => $veggies,
‘meat’ => $meats,
‘dair’ => $dairy
);

 

Accessing Individual Elements of Multidimensional Arrays

$food[‘veg’][1]

print “Eat your {$food[‘veg’][1]}“;

Once again note the all-important Curly Braces!

 

Displaying All Elements of Multidimensional Arrays

foreach ($food as $food_group => $food_item) {
   print “$food_group”;

foreach ($food_item as $index => $food_name)
{
print “Item $index is $food_name”;
}

}

 

Sorting an Array

To sort alpha/numerically by the values:

sort($array)

Or reversed:

rsort($array)

Either of the above destroys the relationship between key and value! Use them only for indexed arrays.

 

To sort values while PRESERVING key/value relationships:

asort($array)

Or reversed:

arsort($array)

 

To sort keys while preserving key/value relationships:

ksort($array)

krsort($array)

 

To randomize (unsort) an array:

shuffle($array)

 

To sort using “natural order:”

natsort($array)

natcasesort($array)

 

Create variables from the values of an array:

$name = array(‘first’ => ‘Glenn’, ‘last’ => ‘Norman’);

extract($name);

print $first; # prints “Glenn”

print $last; # prints “Norman”

extract() is for Associative Arrays.

 

$date = array(‘January’, ’20’, ‘2009’);

list($month, $day, $year) = $date;

list() is for Indexed Arrays.

 

Transformation: Strings to Arrays and Back Again

Turn a string into an array (specifying the separator):

$array = explode($separator, $string);

$array = explode(‘,’, $string);

$array = explode(‘ ‘, $string);

Turn an array into a string :

$string = implode($glue, $array);

$string = implode(‘,’, $array);

$string = implode(‘ ‘, $array);

Also see the join() function, which is identical to implode().

 

A Jillion More Array Functions:

Array Functions at http://www.php.net/manual/en/ref.array.php

 

To do out of class:

Review Chapter 7 of Ullman.