Sie sind auf Seite 1von 68

Lesson 1:

Programming with PHP


Arrays
What Is an Array?
defined as a group of items that share certain
characteristics, such as similarity and type and each is
distinguished by a special identifier, known as a key or
an index so that it can be easily accessed
For example, an array might contain items like state
names, ZIP codes, exam scores, or playing card suits.
a special variable, which can store multiple values in one
single variable name that can be access by referring to
that name

Prepared by: Ma'am Daisy 2


What Is an Array?
An array is consist of 2 items:
Value
Key  used for retrieving the array value
can be numerical or associative

Prepared by: Ma'am Daisy 3


Array Types
Indexed (Numeric) Array
Accessed in accordance with the index position in which
the elements resides
Begin with position 0 not 1
Associative Array
accessed by a key value (word) that bears some sort of
association with its corresponding value
Can be single-dimensional or multi-dimensional
Each object in the array is generally known as Array
element

Prepared by: Ma'am Daisy 4


Indexed Array - Single-dimension
Are handled using an integer subscript to denote the
position of the requested value.
General Syntax:
$name[index1];
Example:
$meat[0] = “beef”;
$meat[1] = “chicken”;
$meat[2] = “fish”;
print $meat[1];
Output: chicken

Prepared by: Ma'am Daisy 5


Indexed Array - Single-dimension
In the following example the index are
automatically assigned
(the index starts at 0):
$cars = array(“Honda","Volvo","BMW","Toyota");

Prepared by: Ma'am Daisy 6


Single-dimension Associative Array
Particularly convenient when it makes more sense to
map an array words rather than integers.
Example:
$person[“name”]=“John Smith”;
$person[“age”]=“24”;
$person[“address”]=“New York”;
$person[“Birthdate”]=“January 1, 1986”;
print $person[“name”];
Output: John Smith

Prepared by: Ma'am Daisy 7


Single-dimension Associative Array
You can also assign values to the end of
the array by simply assigning values to an
array variable using empty brackets.
Therefore, another way to assign values to
the $meat array is as follows:
$meat[] = “beef”;
$meat[] = “chicken”;
$meat[] = “fish”;
Prepared by: Ma'am Daisy 8
Array Pointer
acts like a bookmark that tells about the
position of the array that is presently
examined

Prepared by: Ma'am Daisy 9


Multi-dimensional Indexed Arrays
More than one indexed array is used to
specify an element.
There is no limit as to the dimension size,
although it is unlikely that anything beyond
three dimensions would be used in in most
applications.
General Syntax:
$name[index1][index2]..[indexN];
Prepared by: Ma'am Daisy 10
Multi-dimensional Indexed Arrays
An element of 2D indexed array can be
referred as follows:

$position = $chess_board[5][4];

Prepared by: Ma'am Daisy 11


Multi-dimensional Associative Arrays
Example:
$pairings[“Martinelli”][“zinfandel”]=“Broiled Veal Chops”;
$pairings[“Beringer”][“merlot”]=“Baked Ham”;
$pairings[“Jarvis”][“sauvignon”]=“Prime Rib”;
$pairings[“Climens”][“sauternes”]=“Roasted Salmon”;
print $pairings [“Beringer”][“merlot”];

Prepared by: Ma'am Daisy 12


Mixing Indexed & Associative Array
Indexes
Example:
$Buckeyes[“quarterback”][1] = “Bellisari”;
$Buckeyes[“quarterback”][2] = “Moherman”;
$Buckeyes[“quarterback”][3] = “Wiley”;

Prepared by: Ma'am Daisy 13


Outputting Arrays
print_r()function
boolean print_r(mixed variable [, boolean
return])
takes as input any variable and sends its contents to
standard output, returning TRUE on success and FALSE
otherwise
organize an array’s into a very readable format before
displaying them

Prepared by: Ma'am Daisy 14


Outputting Arrays
For example, suppose you wanted to view the contents
of an associative array consisting of states and their
corresponding state capitals.
You could call print_r()like this:
print_r($states);

This returns the following:


Array ([Ohio] => Columbus [Iowa] => Des Moines
[Arizona] => Phoenix )

Prepared by: Ma'am Daisy 15


Outputting Arrays
The optional parameter return modifies the
function’s behavior, causing it to return the output to
the caller, rather than sending it to standard output.
Therefore, if you want to return the contents of the
preceding $states array, you just set return to
TRUE:

$stateCapitals = print_r($states, TRUE);

Prepared by: Ma'am Daisy 16


Creating an Array
PHP doesn’t require that you assign a size to an array at
creation time
PHP doesn’t even require that you declare the array
before you use it.
Despite the lack of restriction, PHP offers both formal
and informal array declaration methodologies.
Each has its advantages, and both are worth learning.

Prepared by: Ma'am Daisy 17


Creating an Array
Individual elements of a PHP array are referenced by
denoting the element between a pair of square brackets
‘[]’.
Because there is no size limitation on the array, you can
create the array simply by making reference to it, like
this:
$state[0] = "Delaware";
You can then display the first element of the array $state
like this:
echo $state[0];

Prepared by: Ma'am Daisy 18


Creating an Array
You can then add additional values by mapping each
new value to an array index, like this:

$state[1] = "Pennsylvania";
$state[2] = "New Jersey";
...
$state[49] = "Hawaii";

Prepared by: Ma'am Daisy 19


Creating an Array
Interestingly, if you assume the index value is numerical
and ascending, you can choose to omit the index value
at creation time:

$state[] = "Pennsylvania";
$state[] = "New Jersey";
...
$state[] = "Hawaii";

Prepared by: Ma'am Daisy 20


Creating an Array
Creating associative array in this fashion is
equally trivial, except that the associative
index reference is always required.

Prepared by: Ma'am Daisy 21


Creating an Array
The following example creates an array that matches
U.S. state names with their date of entry into the Union:

$state["Delaware"] = "December 7, 1787";


$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
...
$state["Hawaii"] = "August 21, 1959";

Prepared by: Ma'am Daisy 22


Using PHP’s array() function
array array([item1 [,item2 ... [,itemN]]])
Takes as input zero or more elements and
returns an array made up of these input
elements.
Syntax:
array array ([element1], [element2],…)

Prepared by: Ma'am Daisy 23


Using PHP’s array() function for
Indexed arrays
Sample:
$meat = array(“chicken”,“steak”,“turkey”);
print $meat[1];

Output: steak

Prepared by: Ma'am Daisy 24


Using PHP’s array() function for
associative arrays
Example:
$pairings = array(
“zinfandel”=>“Broiled Veal Chops”,
“merlot”=>”Baked Ham”,
“sauvignon”=>“Prime Rib”,
“sauternes”=>“Roasted Salmon”);
print $pairings[“merlot”];

Prepared by: Ma'am Daisy 25


The foreach loop
used to loop through arrays
a statement that provides another way to cycle through
the values in an array, when the index of each item is not
of particular interest
pulling each key/value pair from the array until all items
have been retrieved, or some other internal conditional
has been met

Prepared by: Ma'am Daisy 26


The foreach loop
Two syntax variations are available, each of which is
presented with an example.

Prepared by: Ma'am Daisy 27


The foreach loop
Syntax: (the first variant)
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array
element is assigned to $value (and the array pointer is
moved by one) - so on the next loop iteration, you'll be
looking at the next array value.

Prepared by: Ma'am Daisy 28


Example
The following example demonstrates a loop that will print the values
of the given array:

<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br />";
}
?>

Prepared by: Ma'am Daisy 29


The foreach loop
The second variation is well-suited for working with both
the key and value of an array.
The syntax follows:

foreach ($array_expr as $key => $value)


{
statement
}

Prepared by: Ma'am Daisy 30


The foreach loop
Revising the previous example, suppose that the $links
array contained both a link and corresponding link title:

$links = array(
"The Official Apache Web site" => "www.apache.org",
“The Apress corporate Web site" => "www.apress.com",
"The Official PHP Web site" => "www.php.net");

Prepared by: Ma'am Daisy 31


The foreach loop
Each array item consists of both a key and a
corresponding value.
The foreach statement can easily peel each key/value
pair from the array, like this:

echo "<b>Online Resources</b>:<br />";


foreach($links as $title => $link) {
echo "<a href=\"http://$link\">$title</a><br />";
}

Prepared by: Ma'am Daisy 32


The foreach loop
The result would be that each link is embedded under its
respective title, like this:

Online Resources:<br />


<a href="http://www.apache.org">The Official
Apache Web site</a><br />
<a href="http://www.apress.com">The Apress
corporate Web site</a><br />
<a href="http://www.php.net">The Official PHP
Web site</a><br />

Prepared by: Ma'am Daisy 33


Handling arrays from html form inputs
to PHP scripts
HTML form with array

<input type=”checkbox” name=”selected_ids[]” value=”1″>


<input type=”checkbox” name=”selected_ids[]” value=”2″>
<input type=”checkbox” name=”selected_ids[]” value=”3″>
<input type=”checkbox” name=”selected_ids[]” value=”11″>
<input type=”checkbox” name=”selected_ids[]” value=”12″>
<input type=”checkbox” name=”selected_ids[]” value=”13″>

Prepared by: Ma'am Daisy 34


Handling arrays from html form inputs
to PHP scripts
When the form is submitted, it will generate
$_POST['selected_ids'][] array to the form handling
php script.

This array holds all selected checkbox values from the


form.

foreach() construct can be used to extract values from


the array.

Prepared by: Ma'am Daisy 35


Handling arrays from html form inputs
to PHP scripts
Following code example will show how we
can extract those values from the returning
array.
foreach ($_POST['selected_ids']
as $key => $value) {
echo “Key: $key; Value: $value<br>”;
}

Prepared by: Ma'am Daisy 36


Handling arrays from html form inputs
to PHP scripts
for example if 1,2 and 12 is selected from
the form then the code will print:

Key: 0 Value: 1
Key: 1 Value: 2
Key: 2 Value: 12

Prepared by: Ma'am Daisy 37


Adding and Removing Array Elements
PHP provides a number of functions for both growing
and shrinking an array.
Some of these functions are provided as a convenience
to programmers who wish to mimic various queue
implementations (FIFO, LIFO, and so on), as reflected
by their names (push, pop, shift, and unshift).

Prepared by: Ma'am Daisy 38


Adding and Removing Array Elements
You can add array elements simply by executing the
assignment, like so:
$states["Ohio"] = "March 1, 1803";
In the case of a numerical index, you can append a new
element like this:
$state[] = "Ohio";
Sometimes, however, you’ll require a somewhat more
sophisticated means for adding array elements.

Prepared by: Ma'am Daisy 39


Adding and Removing Array
Elements
array_push()function
int array_push(array target_array, mixed variable
[, mixed variable...])
adds variable onto the end of the target_array, returning
TRUE on success and FALSE otherwise.
You can push multiple variables onto the array
simultaneously, by passing these variables into the function
as input parameters

Prepared by: Ma'am Daisy 40


Adding and Removing Array Elements
Example (in using the
array_push()function):

$states = array("Ohio","New York");


array_push($states,"California","Texas");
// $states = array("Ohio","New York","California","Texas");

Prepared by: Ma'am Daisy 41


Adding and Removing Array Elements
array_pop() function:
mixed array_pop(array target_array)
returns the last element from target_array, resetting the
array pointer upon completion.
Example:

$states=array("Ohio","New York","California","Texas");
$state = array_pop($states);
// $state = "Texas"

Prepared by: Ma'am Daisy 42


Locating Array Elements
in_array()function
boolean in_array(mixed needle, array haystack
[,boolean strict])
searches the array haystack for needle, returning
TRUE if found, and FALSE otherwise
The optional third parameter, strict, forces in_array()
to also consider type.

Prepared by: Ma'am Daisy 43


Locating Array Elements
Example:
$grades = array(100,94.7,67,89,100);
if (in_array("100",$grades))
echo "Sally studied for the test!";
if (in_array("100",$grades,1))
echo "Joe studied for the test!";
Output: Sally studied for the test!
This string will be displayed only once, because the second test
required that the datatypes match. Because the second test
compared an integer with a string, the test failed.

Prepared by: Ma'am Daisy 44


Locating Array Elements
array_keys() function
array array_keys(array target_array [, mixed
search_value])
returns an array consisting of all keys located in the
array target_array.
If the optional search_value parameter is included,
only keys matching that value will be returned.

Prepared by: Ma'am Daisy 45


Locating Array Elements
Example:

$state["Delaware"] = "December 7, 1787";


$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
$keys = array_keys($state);
print_r($keys);
// Array ( [0] => Delaware [1] => Pennsylvania [2] => New Jersey )

Prepared by: Ma'am Daisy 46


Locating Array Elements
array_key_exists()function
boolean array_key_exists(mixed key, array
target_array)
returns TRUE if the supplied key is found in the array
target_array, and returns FALSE otherwise.

Prepared by: Ma'am Daisy 47


Locating Array Elements
Example:

$state["Delaware"] = "December 7, 1787";


$state["Pennsylvania"] = "December 12, 1787";
$state["Ohio"] = "March 1, 1803";
if (array_key_exists("Ohio", $state)) echo "Ohio
joined the Union on $state[Ohio]";

Output: Ohio joined the Union on March 1, 1803

Prepared by: Ma'am Daisy 48


Locating Array Elements
array_values()function
array array_values(array target_array)
returns all values located in the array target_array,
automatically providing numeric indexes for the returned array.
For example:
$population = array("Ohio" => "11,421,267",
"Iowa" => "2,936,760");
$popvalues = array_values($population);
print_r($popvalues);
// Array ( [0] => 11,421,267 [1] => 2,936,760 )

Prepared by: Ma'am Daisy 49


Locating Array Elements
array_search() function
mixed array_search(mixed needle, array haystack [,
boolean strict])
searches the array haystack for the value needle, returning its key
if located, and FALSE otherwise.
For example:
$state["Ohio"] = "March 1";
$state["Delaware"] = "December 7";
$state["Pennsylvania"] = "December 12";
$founded = array_search("December 7", $state);
if ($founded) echo "The state $founded was founded on
$state[$founded]";

Prepared by: Ma'am Daisy 50


Traversing Arrays
key() function
mixed key(array input_array)
returns the key element located at the current pointer position of
input_array.
Consider the following example:
$capitals = array("Ohio"=>"Columbus","Iowa"=>"Des
Moines“,"Arizona"=>"Phoenix");
echo "<p>Can you name the capitals of these states?</p>";
while($key = key($capitals)) {
echo $key."<br />";
next($capitals); }

Prepared by: Ma'am Daisy 51


Traversing Arrays
Output: Ohio
Iowa
Arizona
Note that key() does not advance the pointer with
each call. Rather, you use the next() function, whose
sole purpose is to accomplish this task.

Prepared by: Ma'am Daisy 52


Traversing Arrays
reset() function
mixed reset(array input_array)
serves to set the input_array pointer back to
the beginning of the array.
commonly used when you need to review or
manipulate an array multiple times within a
script, or when sorting has completed

Prepared by: Ma'am Daisy 53


Traversing Arrays
current() function
mixed current(array target_array)
returns the array value residing at the current pointer position of
the target_array
Note that unlike the next(), prev(), and end() functions,
current() does not move the pointer.
An example follows:
$fruits = array("apple", "orange", "banana");
$fruit = current($fruits); // returns "apple"
$fruit = next($fruits); // returns "orange"
$fruit = prev($fruits); // returns "apple"

Prepared by: Ma'am Daisy 54


Traversing Arrays
end() function
mixed end(array target_array)
moves the pointer to the last position of the target_array,
returning the last element.
An example follows:
$fruits = array("apple", "orange", "banana");
$fruit = current($fruits); // returns "apple"
$fruit = end($fruits); // returns "banana"

Prepared by: Ma'am Daisy 55


Traversing Arrays
next() function
mixed next(array target_array)
returns the array value residing at the position
immediately following that of the current array pointer
An example follows:
$fruits = array("apple", "orange", "banana");
$fruit = next($fruits); // returns "orange"
$fruit = next($fruits); // returns "banana"

Prepared by: Ma'am Daisy 56


Traversing Arrays
prev() function
mixed prev(array target_array)
returns the array value residing at the location
preceding the current pointer location, or FALSE if the
pointer resides at the first position in the array

Prepared by: Ma'am Daisy 57


Determining Array Size and
Uniqueness
count() function
integer count(array input_array [, int mode])
returns the total number of values found in the
input_array.
If the optional mode parameter is enabled (set to 1),
the array will be counted recursively, a feature useful
when counting all elements of a multidimensional
array.

Prepared by: Ma'am Daisy 58


Determining Array Size and
Uniqueness
The first example counts the total number of vegetables
found in the $garden array:

$garden = array("cabbage", "peppers",


turnips", "carrots");
echo count($garden);

This returns: 4
Note:
The sizeof() function is an alias of count(). It is
functionally identical.
Prepared by: Ma'am Daisy 59
Determining Array Size and
Uniqueness
The next example counts both the scalar values
and arrays found in $locations:

$locations = array("Italy", "Amsterdam“,


array("Boston","Des Moines"),"Miami");
echo count($locations,1);
This returns: 6
The array entity holding “Boston” and “Des
Moines” is counted as an item, just as its
contents are.

Prepared by: Ma'am Daisy 60


Determining Array Size and
Uniqueness
array_unique() function
array array_unique(array input_array)
removes all duplicate values found in input_array, returning
an array consisting of solely unique values.
Example:
$states = array("Ohio", "Iowa", "Arizona", "Iowa",
"Ohio");
$uniqueStates = array_unique($states);
print_r($uniqueStates);
This returns:
Array ( [0] => Ohio [1] => Iowa [2] => Arizona )

Prepared by: Ma'am Daisy 61


2Predefined language constructs use to create an
array
1. array ()
2. list ()

Prepared by: Ma'am Daisy 62


Using PHP’s list() function
void list(mixed...)
similar to array()
used to make simultaneous variable assignments from
values extracted from an array in just one operation
useful when you’re extracting information from a
database or file

Prepared by: Ma'am Daisy 63


Using PHP’s list() function
For example, suppose you wanted to format and output
information read from a text file.
Each line of the file contains user information, including
name, occupation, and favorite color, with each item
delimited by a vertical bar.
A typical line would look similar to the following:

Nino Sanzi|Professional Golfer|green

Prepared by: Ma'am Daisy 64


Using PHP’s list() function
Using list(), a simple loop could read each line,
assign each piece of data to a variable, and format and
display the data as needed.

Prepared by: Ma'am Daisy 65


Using PHP’s list() function
Here’s how you could use list() to make multiple variable
assignments simultaneously:
// While the EOF hasn't been reached, get next line
while ($line = fgets ($user_file, 4096)) {
// use explode() to separate each piece of data.
list ($name, $occupation, $color) = explode
("|", $line);
// format and output the data
print "Name: $name <br />";
print "Occupation: $occupation <br />";
print "Favorite color: $color <br />";
}

Prepared by: Ma'am Daisy 66


Using PHP’s list() function
Each line would in turn be read and formatted similar to
this:
Name: Nino Sanzi
Occupation: Professional Golfer
Favorite Color: green

Prepared by: Ma'am Daisy 67


Using PHP’s list() function
Reviewing the example, list() depends on the
function explode() to split each line into three
elements, which explode() does by using the vertical
bar as the element delimiter.
These elements are then assigned to $name,
$occupation, and $color.
At that point, it’s just a matter of formatting for display to
the browser.

Prepared by: Ma'am Daisy 68