Difference between revisions of "PHP108"
(11 intermediate revisions by 4 users not shown) | |||
Line 1: | Line 1: | ||
+ | [[Main Page]] >> [[CP2228|Web Application Development]] >> [[PHP|Workbook]] >> Arrays | ||
+ | |||
== PHP Arrays == | == PHP Arrays == | ||
=== What is an array? === | === What is an array? === | ||
− | So far, we have seen how to store a piece of data as a variable. If we wanted to store the name of a student we might use a variable called $student_name. If we had to store the names of three students we might use variables $student_name1, $student_name2 and $student_name3. It is easy to see how this could become inefficient, if not confusing. The structure we can use to simplify | + | So far, we have seen how to store a piece of data as a variable. If we wanted to store the name of a student we might use a variable called $student_name. If we had to store the names of three students we might use variables $student_name1, $student_name2 and $student_name3. It is easy to see how this could become inefficient, if not confusing. The structure we can use to simplify this is an array of variables, just called an 'array'. The following two diagrams contrast storing data in separate variables, compared to using an array. |
− | * | + | * Separate Variables |
− | $student1="Jasmin"; | + | $student1 = "Jasmin"; |
− | $student2="Pardeep"; | + | $student2 = "Pardeep"; |
− | $student3="Simon"; | + | $student3 = "Simon"; |
* Array | * Array | ||
− | $student[1]="Jasmin"; | + | $student[1] = "Jasmin"; |
− | $student[2]="Pardeep"; | + | $student[2] = "Pardeep"; |
− | $student[3]="Simon"; | + | $student[3] = "Simon"; |
== Arrays in PHP == | == Arrays in PHP == | ||
Line 33: | Line 35: | ||
The following example code shows how to create an array, how to 'populate' it and how to access individual elements within the array. | The following example code shows how to create an array, how to 'populate' it and how to access individual elements within the array. | ||
− | <nowiki><? | + | <nowiki><?php |
− | $primes = array(1,2,3,5,7,11,13); | + | $primes = array(1, 2, 3, 5, 7, 11, 13); |
− | $words = ("Wolverhampton", "Computing", "University", "PHP"); | + | $words = array("Wolverhampton", "Computing", "University", "PHP"); |
// Print the third element from the array of primes | // Print the third element from the array of primes | ||
− | echo $primes[2]; | + | echo $primes[2]."<BR>"; |
// Print the second element in the array of words | // Print the second element in the array of words | ||
echo $words[1]; | echo $words[1]; | ||
− | + | ?></nowiki> | |
'''Note:''' - since, by default, the first element of the array is zero, the second element is stored in [1], the fifth element is in [4] etc. Also note the use of square parentheses. | '''Note:''' - since, by default, the first element of the array is zero, the second element is stored in [1], the fifth element is in [4] etc. Also note the use of square parentheses. | ||
Line 52: | Line 54: | ||
We can easily assign values to individual elements of the array, as is shown | We can easily assign values to individual elements of the array, as is shown | ||
− | <nowiki><? | + | <nowiki><?php |
$rainbow[0] = "Red"; | $rainbow[0] = "Red"; | ||
$rainbow[1] = "Orange"; | $rainbow[1] = "Orange"; | ||
Line 59: | Line 61: | ||
// error to be corrected at element 2 | // error to be corrected at element 2 | ||
$rainbow[2] = "Yellow"; | $rainbow[2] = "Yellow"; | ||
− | + | ?></nowiki> | |
Since some people find counting from zero confusing, or it does not 'map' readily to the real world example being modelled, it is possible to start the array at element one (rather than zero). For example: | Since some people find counting from zero confusing, or it does not 'map' readily to the real world example being modelled, it is possible to start the array at element one (rather than zero). For example: | ||
− | <nowiki><? | + | <nowiki><?php |
$counting_numbers = array(1=>"one", "two", "three"); | $counting_numbers = array(1=>"one", "two", "three"); | ||
− | + | ?></nowiki> | |
== The Empty Array == | == The Empty Array == | ||
Line 71: | Line 73: | ||
It is possible to declare an empty array, and indeed such a structure can be useful. A good example is if we want to log error messages which have been generated and store them in an array, the code might be similar to: | It is possible to declare an empty array, and indeed such a structure can be useful. A good example is if we want to log error messages which have been generated and store them in an array, the code might be similar to: | ||
− | <nowiki><? | + | <nowiki><?php |
// declare an empty array | // declare an empty array | ||
$phones = array(); | $phones = array(); | ||
Line 85: | Line 87: | ||
// to test if there have been any inputs in the array | // to test if there have been any inputs in the array | ||
− | if (empty($phones)) | + | if (empty($phones)) { |
− | |||
echo "No phones added"; | echo "No phones added"; | ||
− | } | + | } else { |
− | |||
− | |||
echo "There are phones in the array."; | echo "There are phones in the array."; | ||
} | } | ||
− | + | ?></nowiki> | |
'''Note:''' - in the example the phones are added to the elements 0 and 1 | '''Note:''' - in the example the phones are added to the elements 0 and 1 | ||
Line 105: | Line 104: | ||
Why would I want to use arrays rather than just regular variables? Imagine this: You are working with customer's names. You have 9 of them that you continually need to echo out. With regular variables, you would do it like this: | Why would I want to use arrays rather than just regular variables? Imagine this: You are working with customer's names. You have 9 of them that you continually need to echo out. With regular variables, you would do it like this: | ||
− | <nowiki><? | + | <nowiki><?php |
echo "$customer1<BR>\n"; | echo "$customer1<BR>\n"; | ||
echo "$customer2<BR>\n"; | echo "$customer2<BR>\n"; | ||
Line 115: | Line 114: | ||
echo "$customer8<BR>\n"; | echo "$customer8<BR>\n"; | ||
echo "$customer9<BR>\n"; | echo "$customer9<BR>\n"; | ||
− | + | ?></nowiki> | |
Even with only nine customers this is proving to be long winded. Imagine doing that with 100 customers. Or 1000. With arrays, you can use a 'foreach' loop. What a foreach loop does is loop as many times as you have elements in an array. | Even with only nine customers this is proving to be long winded. Imagine doing that with 100 customers. Or 1000. With arrays, you can use a 'foreach' loop. What a foreach loop does is loop as many times as you have elements in an array. | ||
Line 121: | Line 120: | ||
Suppose you had an array called $customer that contained your customer names. | Suppose you had an array called $customer that contained your customer names. | ||
− | <nowiki><? | + | <nowiki><?php |
− | foreach ($customer as $value) | + | foreach ($customer as $value) { |
− | |||
echo "$value<BR>"; | echo "$value<BR>"; | ||
} | } | ||
− | + | ?></nowiki> | |
This is clearly an easier and more efficient way to access the array than to do so by accessing each element separately (as in the example of five customers). That code will not change if you have 100 or 1000 customers. That's the power of arrays. | This is clearly an easier and more efficient way to access the array than to do so by accessing each element separately (as in the example of five customers). That code will not change if you have 100 or 1000 customers. That's the power of arrays. | ||
Line 134: | Line 132: | ||
What about multi-dimensional arrays? What are they? Let's take a look at a two-dimensional array as an example. Say you are dealing with selling books. You want to place the names and prices of these books into an array. What you would want to do is create an array where each element is an array. Sound confusing? It really isn't. Take a look at this example: | What about multi-dimensional arrays? What are they? Let's take a look at a two-dimensional array as an example. Say you are dealing with selling books. You want to place the names and prices of these books into an array. What you would want to do is create an array where each element is an array. Sound confusing? It really isn't. Take a look at this example: | ||
− | <nowiki><? | + | <nowiki><?php |
$books = array | $books = array | ||
( | ( | ||
− | 0=>array('name'='A Book','price'=>9.99), | + | 0=>array('name'=>'A Book','price'=>9.99), |
− | 1=>array('name'='Another Book','price'=>17.99) | + | 1=>array('name'=>'Another Book','price'=>17.99) |
); | ); | ||
− | + | echo $books[0]['name']."<BR>"; | |
+ | echo $books[1]['price']; | ||
+ | ?></nowiki> | ||
Now, here are a couple ways to access that data in our two-dimensional array: | Now, here are a couple ways to access that data in our two-dimensional array: | ||
− | <nowiki><? | + | <nowiki><?php |
− | + | $books[0]['name'] = 'Harry Potter'; | |
− | |||
$books[0]['price'] = 12.99; | $books[0]['price'] = 12.99; | ||
− | foreach ($books as $thisBook) | + | $books[1]['name'] = 'Bob the Builder'; |
− | + | $books[1]['price'] = 6.99; | |
+ | |||
+ | foreach ($books as $thisBook) { | ||
echo $thisBook['name'] . " sells for $". $thisBook['price'] . "<BR>"; | echo $thisBook['name'] . " sells for $". $thisBook['price'] . "<BR>"; | ||
} | } | ||
− | + | ?></nowiki> | |
So, as we have seen - it may be necessary to model data which can not be easily stored in a simple array. The classic example is the chessboard. In a game of chess we need to know which pieces are stored on which squares. Since the chess board has eight rows of eight squares, we need two parameters to determine which square on the chessboard we are referring to, ie the row and column. The other classic example is a theatre seating plan, which stores the row and the seat number in the row. | So, as we have seen - it may be necessary to model data which can not be easily stored in a simple array. The classic example is the chessboard. In a game of chess we need to know which pieces are stored on which squares. Since the chess board has eight rows of eight squares, we need two parameters to determine which square on the chessboard we are referring to, ie the row and column. The other classic example is a theatre seating plan, which stores the row and the seat number in the row. | ||
Line 167: | Line 168: | ||
<body bgcolor="#ffffff"> | <body bgcolor="#ffffff"> | ||
<h2>A two dimensional array</h2> | <h2>A two dimensional array</h2> | ||
− | + | <?php | |
// A two dimensional array using integer indexes | // A two dimensional array using integer indexes | ||
$planets = array | $planets = array | ||
Line 178: | Line 179: | ||
// prints "Earth" | // prints "Earth" | ||
print $planets[2][0]; | print $planets[2][0]; | ||
− | ? | + | ?> |
− | + | <h2>More sophisticated multi-dimensional array</h2> | |
− | <? | + | <?php |
// More sophisticated multi-dimensional array | // More sophisticated multi-dimensional array | ||
$planets2 = array | $planets2 = array | ||
Line 192: | Line 193: | ||
// prints "Moon" | // prints "Moon" | ||
print $planets2["Earth"]["moons"][0]; | print $planets2["Earth"]["moons"][0]; | ||
− | ? | + | ?> |
</body> | </body> | ||
</html></nowiki> | </html></nowiki> | ||
Line 201: | Line 202: | ||
== Ready to move on? == | == Ready to move on? == | ||
− | [[ | + | [[PHP108 And A Half|PHP108 And A Half - Predefined Variables]] |
Latest revision as of 13:31, 29 June 2016
Main Page >> Web Application Development >> Workbook >> Arrays
PHP Arrays
What is an array?
So far, we have seen how to store a piece of data as a variable. If we wanted to store the name of a student we might use a variable called $student_name. If we had to store the names of three students we might use variables $student_name1, $student_name2 and $student_name3. It is easy to see how this could become inefficient, if not confusing. The structure we can use to simplify this is an array of variables, just called an 'array'. The following two diagrams contrast storing data in separate variables, compared to using an array.
- Separate Variables
$student1 = "Jasmin"; $student2 = "Pardeep"; $student3 = "Simon";
- Array
$student[1] = "Jasmin"; $student[2] = "Pardeep"; $student[3] = "Simon";
Arrays in PHP
PHP uses arrays in a more sophisticated manner than most high-level programming languages. It is also quite flexible in what you can do with them. The individual elements of an array may be accessed by a numeric index (as above), which is known as numbered, or by means of a text string, associative.
The array can hold scalar values:
- Integers
- Booleans
- Strings
- Floats
It can also hold compound values
- Objects
- Other Arrays
Creating an Array
The following example code shows how to create an array, how to 'populate' it and how to access individual elements within the array.
<?php $primes = array(1, 2, 3, 5, 7, 11, 13); $words = array("Wolverhampton", "Computing", "University", "PHP"); // Print the third element from the array of primes echo $primes[2]."<BR>"; // Print the second element in the array of words echo $words[1]; ?>
Note: - since, by default, the first element of the array is zero, the second element is stored in [1], the fifth element is in [4] etc. Also note the use of square parentheses.
Assigning Values to Elements of the Array
We can easily assign values to individual elements of the array, as is shown
<?php $rainbow[0] = "Red"; $rainbow[1] = "Orange"; $rainbow[2] = "Blue"; $rainbow[3] = "Green"; // error to be corrected at element 2 $rainbow[2] = "Yellow"; ?>
Since some people find counting from zero confusing, or it does not 'map' readily to the real world example being modelled, it is possible to start the array at element one (rather than zero). For example:
<?php $counting_numbers = array(1=>"one", "two", "three"); ?>
The Empty Array
It is possible to declare an empty array, and indeed such a structure can be useful. A good example is if we want to log error messages which have been generated and store them in an array, the code might be similar to:
<?php // declare an empty array $phones = array(); // at some point an error is generated, and is to be stored $phones[] = "Matarola Raiser"; // later still $phones[] = "Nuukeya 0001"; // to test if there have been any inputs in the array if (empty($phones)) { echo "No phones added"; } else { echo "There are phones in the array."; } ?>
Note: - in the example the phones are added to the elements 0 and 1
Associative Arrays
Associative arrays give you the ability to name your array's keys. So, instead of having $array[0] and $array[1] you can have $array['aName'] and $array['anotherName'].
A Simple Array
Why would I want to use arrays rather than just regular variables? Imagine this: You are working with customer's names. You have 9 of them that you continually need to echo out. With regular variables, you would do it like this:
<?php echo "$customer1<BR>\n"; echo "$customer2<BR>\n"; echo "$customer3<BR>\n"; echo "$customer4<BR>\n"; echo "$customer5<BR>\n"; echo "$customer6<BR>\n"; echo "$customer7<BR>\n"; echo "$customer8<BR>\n"; echo "$customer9<BR>\n"; ?>
Even with only nine customers this is proving to be long winded. Imagine doing that with 100 customers. Or 1000. With arrays, you can use a 'foreach' loop. What a foreach loop does is loop as many times as you have elements in an array.
Suppose you had an array called $customer that contained your customer names.
<?php foreach ($customer as $value) { echo "$value<BR>"; } ?>
This is clearly an easier and more efficient way to access the array than to do so by accessing each element separately (as in the example of five customers). That code will not change if you have 100 or 1000 customers. That's the power of arrays.
Multidimensional Arrays
What about multi-dimensional arrays? What are they? Let's take a look at a two-dimensional array as an example. Say you are dealing with selling books. You want to place the names and prices of these books into an array. What you would want to do is create an array where each element is an array. Sound confusing? It really isn't. Take a look at this example:
<?php $books = array ( 0=>array('name'=>'A Book','price'=>9.99), 1=>array('name'=>'Another Book','price'=>17.99) ); echo $books[0]['name']."<BR>"; echo $books[1]['price']; ?>
Now, here are a couple ways to access that data in our two-dimensional array:
<?php $books[0]['name'] = 'Harry Potter'; $books[0]['price'] = 12.99; $books[1]['name'] = 'Bob the Builder'; $books[1]['price'] = 6.99; foreach ($books as $thisBook) { echo $thisBook['name'] . " sells for $". $thisBook['price'] . "<BR>"; } ?>
So, as we have seen - it may be necessary to model data which can not be easily stored in a simple array. The classic example is the chessboard. In a game of chess we need to know which pieces are stored on which squares. Since the chess board has eight rows of eight squares, we need two parameters to determine which square on the chessboard we are referring to, ie the row and column. The other classic example is a theatre seating plan, which stores the row and the seat number in the row.
The latter can easily be extended from two dimensions (row, seat number) to three dimensions. The third dimension would be the date. We now have an array capable of storing the details of any seat in the theatre, for any performance by means of these three dimensions (row, seat number, date).
The following example is taken from Web Database Applications with PHP & MySQL By David Lane, Hugh E. Williams.
<html> <head> <title>Multi-dimensional arrays</title> </head> <body bgcolor="#ffffff"> <h2>A two dimensional array</h2> <?php // A two dimensional array using integer indexes $planets = array ( array("Mercury", 0.39, 0.38), array("Venus", 0.72, 0.95), array("Earth", 1.0, 1.0), array("Mars", 1.52, 0.53) ); // prints "Earth" print $planets[2][0]; ?> <h2>More sophisticated multi-dimensional array</h2> <?php // More sophisticated multi-dimensional array $planets2 = array ( "Mercury"=> array("dist"=>0.39, "dia"=>0.38), "Venus" => array("dist"=>0.39, "dia"=>0.95), "Earth" => array("dist"=>1.0, "dia"=>1.0, "moons"=>array("Moon")), "Mars" => array("dist"=>0.39, "dia"=>0.53, "moons"=>array("Phobos", "Deimos")) ); // prints "Moon" print $planets2["Earth"]["moons"][0]; ?> </body> </html>
The first array in the example above is a two-dimensional array, which is accessed using an integer index. The array of planets contains elements which themselves hold an array containing three values the name of the planet, its distance from the sun and the planet diameter (relative to the diameter of earth).
The second array in this example is more sophisticated in so far as it uses associative keys.