Working with Arrays

The following functions let you use arrays in various ways throughout your program.

unset() Function

When you are done working with array values, sometimes it is nice to get rid of them altogether. You might need to use them again later in the program, and want to reuse the keys without worrying about overwriting data. PHP offers the unset() function to get rid of old array values (or, for that matter, old arrays). The function unset() works by only unsetting exactly the parameter you pass to it. Unsetting an array is useful for memory management.

If you want to create an array with five values, you could write something like the following, which ends up looking like Figure 10.5:

Figure 10.5. Before using unset().


<?php

$newarray[]=0;
$newarray[]=1;
$newarray[]=2;
$newarray[]=3;
$newarray[]=4;

echo $newarray[0];
echo $newarray[1];
echo $newarray[2];
echo $newarray[3];
echo $newarray[4];

?>

Now, let’s use unset() on this program:

<?php

$newarray[]=0;
$newarray[]=1;
$newarray[]=2;
$newarray[]=3;
$newarray[]=4;

unset($newarray[2]);
unset($newarray[3]);

echo $newarray[0];
echo $newarray[1];
echo $newarray[2];
echo $newarray[3];
echo $newarray[4];

?>

All we did here was add a couple of lines on unsetting some array items. The result is in Figure 10.6.

Figure 10.6. After using unset() in phpft10-05.php.


If this program gives you an error, that means that your server has its restrictions set very high. This error arises when you try to echo out unset variables. However, this means it is working correctly—an error should occur if your server has strict settings.

This page can be found in phpft10-05.php on the CD. As you see, simply the act of unsetting the variables made trying to echo them impossible, because they did not exist. You could’ve gone one step further, however, and eliminated the entire array by doing this:

unset($newarray);

foreach Loop

The foreach loop is designed distinctly for working with arrays, and if you know how to use it, you can do many more things with arrays. foreach lets you choose any array that you have designed and independently loop through every single item in the array. This is great if you have developed an array of an unknown amount of items and simply want to display the array’s contents as soon as possible.

The foreach loop has two separate structures, both of which you can use at any time. The first structure looks like this:

foreach ($arrayname as $valuename)
{
       //perform statements
}

Take a look at that! I just created a new loop that goes through every single one of the loop’s elements and allows me to access each one. The value $arrayname is the name of the array, and $valuename is an arbitrary variable that is assigned to each individual value of the loop in each iteration.

Let’s see how we might use this. Let’s go back to the web page we made earlier, phpft10-03.php. In this script, we developed a page that would display each month of the year. We used a dozen echo commands to display each one. However, using the foreach loop, we could do this much quicker—more quickly, in fact, than a basic for loop like the one we developed in phpft10-04.php. Check out Figure 10.7 and look at the code that would do this. This page is phpft10-05.php on the CD.

Figure 10.7. Using the foreach loop in phpft10-05.php.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
<title>Using a foreach loop</title>
</head>

<body>

<?php

$newarray = array("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October" , "November", "December");

$variablecounter = 1;
foreach ($newarray as $month)
{
echo "We have iterated through the loop $variablecounter times ==> ";
echo $month . '<br />';
$variablecounter++;
}

?>

</body>
</html>

Hey, pretty cool, huh? We developed the same item and used a variable counter to actually count the number of times we looped through. The counter increments itself each time the loop is iterated, so we see the number of times that every command occurs. This is a lot easier than using the basic for loop, huh? Let’s take a look at the other possible structure you can use for defining foreach loops in your programs:

foreach ($arrayname as $keyname ==> $valuename)
{
          //perform statements
}

A little different declaration. The only major difference here is that we added $keyname; now we can figure out the keys as well as the values. This structure is great for using with forms.

Let’s see a sample. We could develop a form that has several optional items. It can then display the keys and values to help understand which fields were filled in and which the user decided to leave blank. Create a sample form. The following code comes from phpft10-06.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
<title>Using a form with foreach</title>
</head>

<body>
<form name="sampleform" action="phpft10-06.php" method="get">

<h2>Please enter in the following information. All fields are optional. </h2>
Name: <input type="text" name="name">
<br>Address: <input type="text" name="address">
<p>Phone number:
<br><input type="text" name="phone">
<br>I prefer a) <input type="radio" name="prefer" value="cheese">Cheese
<br>b) <input type="radio" name="prefer" value="bread">Bread
<br>c) <input type="radio" name="prefer" value="meat">Meat
<input type="submit">
</form>

</body>
</html>

This page creates a nice-looking form with radio buttons. Check out what this page looks like in Figure 10.8.

Figure 10.8. Creating a form for phpft10-06.html.


Let’s look at the PHP section of phpft10-06.php, which displays the results using PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
<title>Using a foreach loop with forms</title>
</head>

<body>

<?php
$counter = 1;
foreach($_GET as $keyvalue => $realvalue)
{

        echo "Loop has iterated $counter times: ";
        echo "Key: $keyvalue has value: $realvalue" . '<p>' ;
        $counter++;

}

?>

</body>
</html>

This ends up looking like Figure 10.9.

Figure 10.9. Displaying results in phpft10-06.php.


Whoa, look at that. The page displays the proper results by showing the key value and the real value of each element in the $_GET array. Remember that the $_GET array actually is a predefined container that holds all of the elements submitted through the GET method on a form. When we used the form on the last page, we sent all the information through GET to the new page. This page then took that data and looped through each element of the array, displaying the key value and the real value on the screen. With that, we got the results we wanted!

This program properly reports the value of every field of every form with a GET method. This form is not tied to a specific form, and you can use any HTML page to reference this PHP page, and it will display all the elements of your GET array. This is useful to check for errors. Pretty cool, huh?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.253.152