Vous êtes sur la page 1sur 12

ARRAYS with PHP R. B. see chapter 7, Ullman.

An array is a variable that contains multiple values which can be strings, numbers or other arrays.
To create an array:

1)

$fruit = array (apples, pears, oranges, plums)

2)

$fruit = array(); // initialize array use round brackets


$fruit[0] = apples; // assign key to each array element
$fruit[1] = pears;
$fruit[2]= oranges;
$fruit[3]= plums;

3)

Associative Array you associate a string or other value you dont use serial
numbers

$provincialcapital[Edmonton];
$provincialcapital[Toronto];
$provincialcapital[Halifax];
or
$soups = array(
Monday => Clam Chowder,
Tuesday =>White Chicken,
Wednesday => Vegetarian
);
If you try to output the array elements by using the echo or print statement:
<?php
print $soups <br />\n;
?>
You will only see the word Array on the screen the individual values are not echoed to the
screen.

ADDING MORE ELEMENTS TO AN ARRAY - COUNT() function


If you want to see how many elements are in an array you can use the count() function like so:

<?php
$soups = array(
"Monday" => "Clam Chowder",
"Tuesday" => "White Chicken",
"Wednesday" => "Vegetarian",
);
print "$soups <br>\n";
$howmany = count($soups);
print "$howmany";
?>

it will display 3 in this case.

To add more elements to the array:


$soups[Thursday] = Chicken noodle;
$soups[Friday] = Tomato;
$soups[Saturday] = Cream of Broccoli;

$nowhomany = count($soups);
print "$nowhowmany"; // this will output 6 to the screen now.

MERGING ARRAYS array_merge() function


The array_merge() function is new to PHP4 it allows you combine elements of different arrays
into one array.
<?php
$fruits = array("apples", "oranges", "pears");
$vegetables = array("potatoes", "celery", "carrots");
$newarray = array_merge($fruits, $vegetables);
$howmany = count($newarray);
print "$howmany"; // will output 6 to the screen
?>

Note the order you merge the arrays in will determine the order they appear i.e.
array_merge($fruits, $vegetables) will be different from array_merge($vegetables, $fruits).

ACCESSING ARRAY ELEMENTS

To access individual array elements you refer to them by their index number which usually starts
at 0 but you can assign the array to start at any number. With an associative array you refer to
the entire element e.g. $soups[Monday] - not the use of the square brackets.

e.g
in the previous example to view the first vegetable in the array add the code:
print $vegetables[0]; // this will print to the screen potatoes
print $vegetables[1] ; // this will print to the screen celery

You could also assign the array element to a separate variable e.g.
$veg = $vegetables[1];
print $veg; // will output celery to the screen

One of the limitations of arrays is that in order to refer to a specific element you must know the
keys to which the specific element refers to and in the case of associate arrays $soups[1] will not
point to nothing since its value is a string, i.e. $soups[Monday]

FOR LOOPS
To output or access all the elements of an array you can use loops e.g.
<?php
$vegetables = array("potatoes", "celery", "carrots");
for ($i=0; $i< count($vegetables); $i++)
{
print "$vegetables[$i]<br>\n";
}
?>
In this example we used $i < count($vegetables); we could have used $i < 4 - but that requires
you know exactly how many elements are in the array.
The screen output will be:
potatoes
celery
carrots

Using the each() function to reveal the key and value elements in an array
<?php
$vegetables = array("potatoes", "celery", "carrots");
for ($i=0; $i< count($vegetables); $i++)
{
$Line = each($vegetables);
print "$Line[key] is $Line[value]<br>\n";
}
?>

output will look like this:

Here is another example using an associate array.

<?php
$soups = array();
$soups["Monday"] = "Clam Chowder";
$soups["Tuesday"] = "White Chicken";
$soups["Wednesday"] = "Vegetarian";
$soups["Thursday"] = "Chicken Noodle";
$soups["Friday"] = "Tomato";
for ($i=0; $i<count($soups); $i++)
{
print $soups[$i] <br>\n"; // nothing prints to the screen since there are no number keys
}
?>

<?php
$soups = array();
$soups["Monday"] = "Clam Chowder";
$soups["Tuesday"] = "White Chicken";
$soups["Wednesday"] = "Vegetarian";
$soups["Thursday"] = "Chicken Noodle";
$soups["Friday"] = "Tomato";
for ($i=0; $i<count($soups); $i++)
{
$Line = each($soups);
print "$Line $soups[$i] <br>\n"; //this prints the word Array to the screen 5 times
?>
print "$Line[key] <br>\n"; // this will print the key values to the screen: Monday, Tuesday,
Wednesday, Thursday, Friday
print $Line[key]s soup is $Line[value] <br>\n;

The each() function retrieves the keys and the values associated with each key.
each(array) function returns a four-element sub array contain the key and value of the current
element form the specified array.

SORTING ARRAYS

Php provides a variety of functions to sort arrays alphabetically or numerically.

To sort the values in an array without regard to their keys use: sort(0 and rsort(), the latter being
reverse sort.
sort($array)
rsort($array)
To sort the values while keeping the correlation between the value and the key use:
assort($array)
arsort($array) // reverse sort
To sort by the keys while maintaining the correlation between the key and its value:
ksort($array)
krsort($array)
To randomize the order of the array you can use:
Shuffle($array)
<?php
$grades = array();
$grades["Richard"] = 95;
$grades ["Sherwood"] = 82;
$grades ["Toni"] = 98;
$grades ["Fanz"] = 87;
$grades ["Melisa"]= 75;
// use each since it is an associative array
for ($x=0; $x <count($grades); $x++)
{
$Line = each($grades);
print "$Line[key] $Line[value] $grades[$x] <br>\n";
}
?>

Example of sorting an associative array

<?php
$grades = array();
$grades["Richard"] = 95;
$grades ["Sherwood"] = 82;
$grades ["Toni"] = 98;
$grades ["Fanz"] = 87;
$grades ["Melisa"]= 75;
for ($x=0; $x <count($grades); $x++)
{
$Line = each($grades);
print "$Line[key] $Line[value] <br>\n";
}
print "<br>After sorting the array with ksort() function<br> \n";
reset($grades); // returns the pointer to the first element in array
ksort($grades);

for ($x=0; $x <count($grades); $x++)


{
$Line = each($grades);
print "$Line[key] $Line[value] <br>\n";
}
print "<br>using arsort() function<br>\n";
reset($grades);
arsort($grades);
for ($x=0; $x <count($grades); $x++)
{
$Line = each($grades);
print "$Line[key] $Line[value]<br>\n";
}

Transforming Between Strings and Arrays Implode() and Explode() FUNCTIONS


You can convert and array into a string and vice versa. You might want to turn a string into an
array to read information from a text file or database, or you might want to change an array into a
string in order to store the data in a text file or database.
Another possible use is that you might want to convert a comma-delimited text field e.g. keyword
search area of a form into its separate parts.
Explode() syntax
$array = explode($separator, $string);
The separator refers to whatever character(s) define where one array element ends and another
begins. Normally this is a comma or blank space:
Convert array to string:
$array = explode(,, $string);
or
$array = explode( , $string);
Convert string to an array Implode() syntax
$string = implode($glue, $array); // glue is the separator you want to add
$string = implode(,, $array);
$string = implode( , $array);

Exercise: create a form that accepts a comma delimited string of names from the user. Use
php to sort the list of names and display the list on the page. (answer next page).
<html>
<head>
<title>Form</title>
</head>
<body>
<p>Enter the words or names you want alphabetized with each word
separated by an empty space</p>
<form method="post" action="handlelist.php">
<input type="text" name="List" size="80"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
$Array = explode(" ", $List);
// take the values entered in the form text box List and separate them
sort($Array); // sorts the value alphabetically also try rsort()
$Newlist = implode("<br>", $Array);
print "List :<br> $Newlist";
?>
</body>
</html>

Working with Arrays


To change an element in an array
<?php
$fruits = array(apple, banana, orange, grape)
$fruits[0] = apricot; // to change an element type name of array[] include number
$fruits[2] = strawberry;
?>
If you specify a number greater than the largest index number, PHP will not create elements to fill
the gap between the index numbers.
If a new element is added to an array that does not exist, a new array will be created. However, It
is best to create the array first.
You can create an empty array then later add elements to that array. This is useful if you want to
filter array elements or dynamically add elements using data obtained from a form or database.

Creating an Associate Array


When you create an array you do not have to use index numbers
e.g.
$provincialcapital[Edmonton];
$provincialcapital[Toronto];
$provincialcapital[Halifax];
Arrays of this type are known as associate arrays. To access elements in these arrays you simply
refer to them:
Print $provinicalcapital[Halifax];
We could have used abbreviations for the various capital e.g. Ed for Edmonton.
In PHP arrays can even be assigned different data types. E.g.
$Number[1] = 24;
$Number[2] = twenty three;
$Number[3] = $variable;
$Number[ca] = $variable;

= > Array Operator allows you assign the index number you want to start an array. For example if
you had an array of the 50 states you could start the array at 1 like this.
$states = array(1=> Alabama, Alaska, .);

if you wanted to iterate and move through the array you would use a for loop
for ($counter=1; $counter <51; $counter++)
{
echo <br>$states[$counter];
}
You could also use a while loop
$counter = 1;
while ($counter < 510)
{
echo <br>$states[$counter];
$counter++; // or $counter = $counter + 1
}
Exercise:

10

Create a form with a drop down menu, where the user selects a Canadian province or territory
and returns the capital city. Use a for loop to create the select menu.
Province/Territory
1. Yukon Territory
2. Northwest Territory
3. Nunavut
4. British Columbia
5. Alberta
6. Saskatchewan
7. Manitoba
8. Ontario
9. Quebec
10. Prince Edward Island
11. Newfoundland
12. New Brunswick
13. Nova Scotia

Capital city
Whitehorse
Yellowknife
Iqaluit
Victoria
Edmonton
Regina
Winnipeg
Toronto
Quebec City
Charlettetown
St. Johns
Fredericton
Halifax

<html>
<head>
<title>Canadian Provinces and Capitals</title>
</head>
<body>
What province do you want to know the capital city of?<form method="post"
action="capitals.php"><select name="province">
<?php
$provinces = array(1=> "Yukon Territory", "Northwest Territory", "Nunavut", "British Columbia",
"Alberta", "Saskatchewan", "Manitoba", "Ontario", "Quebec", "Prince Edward Island",
"Newfoundland", "New Brunswick", "Nova Scotia");
for ($counter=1; $counter < 14; $counter++)
{

11

echo "<option>$provinces[$counter]</option>";
}
echo "</select>";
for ($counter=1; $counter < 14; $counter++)
{
echo "<input type=hidden name='hiddenprovinces[]' value='$provinces[$counter]'>";
}
echo "<input type=submit name=submit value=Submit></form>";
?>
</body>
</html>
Save file as provinces.php
<html>
<head>
<title>Provincial Capitals</title>
</head>
<body>
<?php
$provincialcapital = array (0=> "White horse", "Yellow Knife", "Iqaluit", "Victoria", "Edmonton",
"Regina", "Winnipeg", "Toronto", "Quebec City", "Charlettetown", "St. John's", "Fredericton",
"Halifax");
for ($counter=0; $counter <14; $counter++)
{
if ($hiddenprovinces[$counter] == $province)
{
echo "The provincial capital of $province is $provincialcapital[$counter]";
}
}
?>
</body>
</html>
Save file as capitals.php

Here is what the output should look like when the user selects Alberta.
Note: The 2nd array starts at 0. This because the hiddenprovinces [] array generated starts at 0.
e.g. print $hiddenprovinces[0] is Yukon Territory and hiddenprovinces[1] is Northwest territories.
If your server has set register_globals=Off you will need to set hiddenprovinces[$counter]
to make the script work properly.

12

Vous aimerez peut-être aussi