Académique Documents
Professionnel Documents
Culture Documents
An array is a variable that contains multiple values which can be strings, numbers or other arrays.
To create an array:
1)
2)
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.
<?php
$soups = array(
"Monday" => "Clam Chowder",
"Tuesday" => "White Chicken",
"Wednesday" => "Vegetarian",
);
print "$soups <br>\n";
$howmany = count($soups);
print "$howmany";
?>
$nowhomany = count($soups);
print "$nowhowmany"; // this will output 6 to the screen now.
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).
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";
}
?>
<?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
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";
}
?>
<?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);
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>
= > 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