Học làm web (x7) - PHP: using arrays

Bài trước: Học làm web (x6) - PHP: storing and retrieving data (cont)
-----

1.3            Using arrays


An array is a variable that stores a set or sequence of values. One array can have many elements, and each element can hold a single value, such as text or numbers, or another array. An array containing other arrays is known as a multidimention array.

PHP supports arrays with both numerical and string indexes.

Numerically indexed arrays (p76)


To create the array with numerical index, use the following line of PHP code:

$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);

Since PHP 5.4, you can use a new shorthand syntax for creating arrays. This uses the [ and ] characters in place of the array() operator. For example,

$products = [‘Tires’, ‘Oil’, ‘Spark Plugs’];

Depending on the contents you need in your array, you might not need to manually initialize them as in the preceding example. If you have the data you need in another array, you can simply copy one array to another using the = operator.

If you want an ascending sequence of numbers stored in an array, you can use the range() function to automatically create the array for you. The following statement creates an array called numbers with elements ranging from 1 to 10.

$numbers = range(1, 10);

The range() function has an optional third parameter that allows you to set the step size between values. For instance, if you want an array of the odd numbers between 1 and 10, you could create it as follows:

$odds = range(1, 10, 2);

The range() function can also be used with character, as in this example:

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

If you have information stored in a file on disk, you can load the array contents directly from the file.
If you have the data for your array stored in a database, you can load the array contents directly from the database.

You can also use various functions to extract part of an array or to reorder an array.

Accessing array contents (p77)

To access the contents of a variable, you use its name. If the variable is an array, you access the contents using both the variable name and a key or index. The key or index indicates which of the values in the array you access. The index is placed in square brackets after the name. In other words, you can use $products[0], $products[1], and $products[2] to access each of the contents of the $products array.

You may also use the {} characters to access array elements instead of the [] characters if you prefer. For example, you could use $products{0} to access the first element of the products array.

By default, element zero is the first element in the array.

As with other variables, you change array elements’ contents by using the = operator. The following line replaces the first element in the array, ‘Tires’, with ‘Fuses’:

$products[0] = ‘Fuses’;

To display the contents, you could type this line:

echo “$products[0] $products[1] $products[2]”;

Like other PHP variables, arrays do not need to be initialized or created in advance. They are automatically created the first time you use them.

The following code creates the same $products array created previously with array() statement:

$products[0] = “Tires”;
$products[1] = “Oil”;
$products[2] = “Spark Plugs”;

If $products does not already exist, the first line will create a new array with just one element. The subsequent lines add values to the array. The array is dynamically resized as you add elements to it. This resizing capability is not present in many other programming languages.

Using loops to access the array (p78)

for ($i = 0; $i<3; $i++) {
echo $products[$i]." ";
}

You can also use the foreach loop, specially designed for use with arrays. In this examply, you could use it as follows:

foreach ($products as $current) {
echo $current." ";
}

Arrays with different indices (p79)


Initializing an array

The following code creates an array with product names as keys and prices as values:

$prices = array(‘Tires’ => 100, ‘Oil’ => 10, ‘Spark Plugs’ => 4);

The symbol between the keys and values (=>) is simply an equal sign immediately followed by a greater than symbol.

Accessing the array elements

Again, you access the contents using the variable name and a key, so you can access the information stored in the prices array as $prices[‘Tires’], $prices[‘Oil’], $prices[‘Spark Plugs’].

The following code creates the same $prices array. Instead of creating an array with three elements, this version creates an array with only one element and then adds two more:

$prices = array(‘Tires’ => 100);
$prices[‘Oil’] = 10;
$prices[‘Spark Plugs’] = 4;

Here is another slightly different but equivalent piece of code. In this version, you do not explicitly create an array at all. The array is created for you when you add the first element to it:

$prices[‘Tires’] = 100;
$prices[‘Oil’] = 10;
$prices[‘Spark Plugs’] = 4;

Using loops

Because the indices in an array are not numbers, you cannot use a simple counter in a for loop to work with the array. However, you can use the foreach loop or the list() and each() constructs.

foreach($prices as $key => $value) {
            echo $key. “ - ”.$value.“<br>”;
}

The following code lists the contents of the $prices array using the each() construct:

while ($element = each($prices)) {
            echo $element[‘key’].“ - ”.element[‘value’];
            echo “<br>”;
}

each() function returns the current element in an array and makes the next element the current one. Because we are calling each() within a while loop, it returns every element in the array in turn and stops when the end of the array is reached.

In this code, the variable $element is an array. When you call each(), it gives you an array with four values and the four indices to the array locations. The location key and 0 contain the key of the current element, and the locations value and 1 contain the value of the current element. Although the one you choose makes no difference, we chose to use the named locations rather than the numbered ones.

There is a more element and common way of doing the same thing. The construct list() can be used to split an array into a number of values. You can separate each set of values that the each() function give you like this:

while (list($product, $price) = each($prices)) {
            echo $product.“ – ”.$price.“<br>”;
}

This line uses each() to take the current element from $prices, return it as an array, and make the next element current. It also uses list() to turn the 0 and 1 elements from the array returned by each() into two new variables called $product and $price.

When you are using each(), note that the array keeps track of the current element. If you want to use the array twice in the same script, you need to set the current element back to the start of the array using the function reset(). To loop through the prices array again, you type the following:

reset($prices);
while (list($product, $price) = each($prices)) {
            echo $product.“ – ”.$price.“<br>”;
}

Lab 11. Create a Select Box.

Create a Select Box by using HTML,

For example,

<div class="content">
                        <select name="group" id="group" style="width: 200px">
                                    <option value="1">Admin</option>
                                    <option value="2">Manager</option>
                                    <option value="3">Member</option>
                                    <option value="4">Guest</option>
                        </select>
            </div>

Then, create above Select Box, but using PHP as the following script,

            <div class="content">
            <?php
                        $group = array('1' => 'Admin', '2' => 'Manager', '3' => 'Member', '4' => 'Guest');
                        $xhtml = '';
           
                        if(!empty($group)) {
                                    $xhtml .= '<select name="group" id="group" style="width: 200px">';
                                    foreach ($group as $key => $value) {
                                                if($key == '3') {
                                                            $xhtml .= '<option value="'.$key.'"selected = "selected">'.$value.'</option>';           
                                                } else {
                                                            $xhtml .= '<option value="'.$key.'">'.$value.'</option>';
                                                }
                                    }
                                    $xhtml .= '</select>';
                        }
                        echo $xhtml;
            ?>                                          
            </div>

When creating a Select Box by using PHP means use a variable contains HTML, then echo HTML then.

You can using a function to create a Select Box for reusing then, for example,

<div class="content">
            <?php
                        $group = array('1' => 'Admin', '2' => 'Manager', '3' => 'Member', '4' => 'Guest');
                        $city  = array('ct' => 'Cần Thơ', 'hg' => 'Hậu Giang', 'bt' => 'Bến Tre');
                        function createSelectbox($name, $attributes, $array, $keySelect) {
                                    $xhtml = '';

                                    if(!empty($array)) {
                                                $xhtml .= '<select name="'.$name.'" id="'.$name.'" style="'.$attributes.'">';
                                                foreach ($array as $key => $value) {
                                                            if($key == $keySelect) {
                                                                        $xhtml .= '<option value="'.$key.'"selected = "selected">'.$value.'</option>';        
                                                            } else {
                                                                        $xhtml .= '<option value="'.$key.'">'.$value.'</option>';
                                                            }
                                                }
                                                $xhtml .= '</select>';
                                    }
                                    return $xhtml;
                        }
                        $groupSelect = createSelectbox('group', 'width: 200px', $group, 4);
                        $citySelect = createSelectbox('city', 'width: 300px', $city, 'hg');
                        echo $groupSelect;
                        echo '<br>';
                        echo $citySelect;
            ?>                                          
            </div>



</////07
-----------
Cập nhật [21/5/2019]
-----------
Xem thêm: Tổng hợp các bài viết về  Học làm web
Xem thêm: Học làm web (x8) - PHP: sorting arrays