3.3 Data Types and Functions


In the previous sections you have already seen that PHP supports variables, but so far you have only learned to use numbers and strings. Just like control structures, data types are a core component of every programming language.

Like most other high-level languages, PHP works to a large extent without types and tries to recognize the data type of a variable by itself. However, PHP provides a set of different data types, as shown in Table 3.1.

Table 3.1. Data Types in PHP
Data Type Description
Int, integer Numeric values with no commas
Double, real Floating-point number
String A sequence of characters
Array A pool of values
Object A artificial, user-defined data type

In this section you will learn to use these data types efficiently.

3.3.1 Variables and Names

As you have already seen in the examples discussed in the previous sections, variables are marked with $ in PHP. Unlike Perl, PHP marks all variables with a $ and does not use @ and % as symbols.

In PHP the names of variables are case sensitive, which means that it makes a difference whether a name is written in capital letters. The name of a variable may start with a letter or an underscore. After the first character, all letters and numbers as well as underscores are allowed. However, we strongly recommend using only letters in the variable name because otherwise programs can be confusing and hard to understand, especially when people start mixing up variables written in either capital letters or lowercase letters.

The next example shows that $a is not equal to $A:

 <?php         $a = "I am a string";         $A = "I am a string as well";         echo "a: $a; A: $A<br>\n"; ?> 

As you can see, in the result, the two strings are not the same.

 a: I am a string; A: I am a string as well 

3.3.2 Automatic Data Type Recognition

When a variable has to be processed by PHP, the interpreter follows some predefined rules in order to recognize which data type a variable has:

  • If a sequence of characters starts and ends with quotes, it will be treated as a string: $a = 'abc' assigns the string abc to $a because the string is enclosed with quotes.

  • If a number does not contain a point, it is treated as an integer value: $a = 23 means that 23 is assigned to $a. The value 23 is an integer value because there is no point in it.

  • If a number contains a point, it will be treated as a floating-point number: $a = 3.14159 makes PHP assign a floating-point value to $a.

Knowing these three rules will make it easy for you to forecast the result of an operation and will make it easier for you to write bug-free applications.

3.3.3 Checking Data Types and Explicit Casting

Sometimes it is necessary to change the data type of a variable explicitly. Although PHP does a lot of type casting internally, it might help in some cases to make sure that a variable is assigned to a certain data type. To perform operations like that, PHP provides the required functions. Before you learn about these functions, you will see how you can find the data type of a variable:

 <?php         $a = 3.14159;         $b = 12;         $c = "I am a string";         $d = array(1, 2, 3);         echo '$a is a '.gettype($a)." value<br>\n";         echo '$b is an '.gettype($b)." value<br>\n";         echo '$c is a '.gettype($c)." value<br>\n";         echo '$d is an '.gettype($d)." value<br>\n"; ?> 

With the help of a function called gettype, it is possible to retrieve the data type of a variable easily. If you use the rules described in the previous section, it will be easy to predict the result of the script:

 $a is a double value $b is an integer value $c is a string value $d is an array value 

The first value is a floating-point value because it contains a comma. The second value is an integer value because it does not contain a comma. The third value is enclosed by quotes and therefore it is treated as a string. The last value is an array because the expression on the right side of the = returns an array of integer values.

Another way to check the data type of a variable is to use a special, data type specific function as shown following:

 <?php         $a = 3.14159;         $b = 12;         $c = "I am a string";         $d = array(1, 2, 3);         echo '$a: '.is_double($a)."<br>\n";         echo '$b: '.is_integer($b)."<br>\n";         echo '$c: '.is_string($c)."<br>\n";         echo '$d: '.is_array($d)."<br>\n";         echo '$d: '.is_object($d)."<br>\n"; ?> 

You use the functions is_double, is_integer, is_string, is_array, and is_object. If the value passed to the function has the appropriate data type, 1 will be returned. The next listing contains the result of the script you have just seen:

 $a: 1 $b: 1 $c: 1 $d: 1 $d: 

All values but the last one are true. The last line shows that $d is not an object.

If you perform an explicit cast, it can easily happen that some of the data stored in the variable you want to cast is lost. This is not a weak point of PHP because casting cannot be done differently by the PHP interpreter. Let's have a look at the next example:

 <?php         $a = 3.14159;         $b = 12;         $a_cast = (int)$a;         $b_cast = (double)$b;         echo "a_cast: $a_cast<br>";         echo "b_cast: $b_cast<br>"; ?> 

$a is a floating-point number that is cast to integer and displayed on the screen. $b is cast to double and displayed on the screen as well. If you have a look at the result, you will see that $a_cast is not as precise as $a_cast because an integer value is not allowed to store digits right of the comma. $b_cast and $b are the same because integers can also be represented as double values without losing data:

 a_cast: 3 b_cast: 12 

Some general rules and hints should be taken into consideration when performing casts. Table 3.2 contains a compilation of the most important information concerning casts.

Table 3.2. Rules in PHP
Data Type of Result Data Type Before the Cast Changes
Integer Double Data right of the point is silently omitted the value is not rounded.
Integer String If no number is recognized, 0 is returned.
Double Integer No changes.
Double String If no number is recognized, 0 is returned.
String Integer Returns the number as a sequence of characters.
String Double Returns the number as a sequence of characters.
Array Object Will be transformed directly.
Array Integer An array of integer values will be created.
Array String An array of string values will be created.
Array Double An array of floating-point values will be created.
Object Array Will be transformed directly.
Object Integer An object with the same properties as an integer value is generated.
Object String An object with the same properties as a string value is generated.
Object Double An object with the same properties as a double value is generated.

From this table, you can easily see which dangers you might have to face when performing typecast operations.

3.3.4 Functions

Functions are the heart of every programming language. They are used to isolate certain tasks of a program and help the programmer to use the same code in various places without having to copy it. Functions can be called with parameters and perform a fixed set of instructions. If necessary, a function can return values to the function or object that has called it.

You have already worked with functions. One of the functions you have dealt with is called gettype, and it returns the data type of a variable. This function is a good example of what the topic is all about. You pass a variable to it and a value will be returned.

In recent years, the word function has lost popularity because in the object-oriented programming paradigm, it no longer exists. As you will see in the chapter about object-oriented PHP (see Chapter 4, "Object-Oriented PHP"), functions are called methods in object-oriented PHP. This makes no difference in the way things work it is just a new name for an old and useful invention.

3.3.5 Output Functions and Working with Strings

Like Pascal, a programming language defined by Prof. Niklaus Wirth at the Eidgenössische Technische Hochschule (ETH) Zürich in 1970, PHP supports a data type called string. Strings are a sequence of characters and are often used to store text. Unlike in C/C++, handling strings is an easy task in PHP because the programmer does not have to take care of memory management and segmentation faults that occur because of problems with memory allocation. This makes PHP suitable for fast and reliable software development.

The list of functions for working with strings in PHP seems to be endless. We will try to cover the most important ones in this section.

To display ASCII characters on the screen, PHP provides a function called chr. Simply pass the ASCII code to the function, and the desired character will be returned. The next example shows how the e-mail address of one of the authors can "easily" be displayed using chr.

 <?php         echo chr(104).chr(115).chr(64).chr(99).chr(121).chr(98).                 chr(101).chr(114).chr(116).chr(101),chr(99).chr(46).                 chr(97).chr(116)."<br>\n"; ?> 

And the result is

 hs@cybertec.at 

I am sure that there are more efficient ways of displaying e-mail addresses; normally chr is used to display characters that cannot be found on the keyboard.

The exact opposite of the chr is the Ord function, which can be used to compute the ASCII value of a character:

 <?php         $a = "a";         echo Ord($a); ?> 

Nowadays encrypting data is an extremely important task because security standards are increasing and hackers might threaten your networks. With the arrival of all those viruses spreading themselves over networks, security has become an important topic. In the next example you will see how a string can easily be encrypted using PHP's onboard functions:

 <?php         $a = "I am a string";         echo crypt($a); ?> 

Simply pass the string you want to process to the crypt function and the result will be encoded using the DES algorithm.

The result will be a string that you won't be able to read:

 i34vSr3Aueg2A 

As you have already seen, HTML code is a pool of special characters having a certain meaning. A good example for that is the < character, which is used to define the starting point of an HTML tag. The problem is: what can you do when you want to display a < character on the screen? The problem can easily be solved using a function called htmlspecialchars, which converts all characters having a certain meaning or which are not allowed to be used in the appropriate HTML code. The next piece of code shows how this works:

 <?php         $b = "1 > 0";         echo htmlspecialchars($b); ?> 

1 > 0 is displayed on the screen, but the HTML code generated by PHP looks slightly different:

 1 &gt; 0 

> has been substituted for &gt; and that's what you wanted it to be.

Another important character in the list of special symbols is the & symbol. In HTML code & has to be coded as &amp;. As you can see, in the next example, the htmlspecialchars function takes care of that issue:

 <?php         $b = "Mr. Schönig & Mr. Müller are from Austria";         echo htmlspecialchars($b)." <br>\n"; ?> 

If you have a look at the HTML code you have generated, you can see that the ampersand has been replaced for &amp;.

 Mr. Schönig &amp; Mr. Müller are from Austria <br> 

printf is the dinosaur of string and text processing. It allows you to display formatted text on the screen. The C programmers among you might already be familiar with printf. The PHP version of printf is very similar to the C function. Let's have a look at an example:

 <?php         $a = "Hans";         printf ("This is the diary of %s.<br>\n", $a);         $b = 23;         printf ("He is %d years old.<br>\n", $b);         printf ("$b can also be written as %b (binary) or %o (octal).<br>",                 $b, $b);         printf ("Let's print $b again but this time as an integer ".                 "printed as a character: %c.<br>", $b, $b);         $b += 2/12;         printf ("To be more precise: %s is $b years and two months old; ".                 "as a floating point number this would be: %5.3f.<br>\n", ?> 

In the first line you define a variable containing the first name of the author. In the next line you want to display this variable as part of a string on the text. Therefore you use printf. %s is substituted for $a. $a is interpreted as a string and will be displayed on the screen as a string. In the next step $b is defined as an integer value. After that $b is displayed as integer value by using %d. In the next line $b is displayed as a binary and as an octal value. This is the first time you use printf with more than just one parameter. Because two substitutions are performed, it is necessary to pass two parameters to printf.

One line later, you try to interpret $b as an integer value printed as a character. In other words, you try to display the character having $b as its ASCII value on the screen.

Finally, you add 2/12 to $b ($b += 2/12 is equal to $b = $b + 2/12) and display $b as a floating-point number using %f. The floating-point number has a total length of five digits, and three of these digits have to be on the right side of the point.

When executing the script, you will receive the this result:

 This is the diary of Hans. He is 23 years old. 23 can also be written as 10111 (binary) or 27 (octal). Let's print 23 again but this time as an integer printed as a character: #. To be more precise: Hans is 23.166666666667 years and two months old; as a floating point number this would be: 23.167. 

Printf supports a lot of formatting instructions. Table 3.3 contains a list of shortcuts supported by printf.

Table 3.3. Formats Accepted by printf
Formatting Meaning
%b Interpret value as an integer but print it as a binary value.
%c Interpret value as an integer but print it as a character.
%d Interpret value as an integer but print it as a decimal value.
%f Interpret value as a double and print it as a floating-point number.
%o Interpret value as an integer but print it as an octal value.
%s Interpret and print as a string.
%x Interpret value as an integer but print it as a hexadecimal value using lowercase letters.
%X Interpret value as an integer but print it as a hexadecimal value using uppercase letters.

Printf returns 0 or 1 depending on whether the command has been executed successfully. If you want to retrieve the string generated by printf, you have to use sprintf instead. In contrast to printf, sprintf returns the string that has been generated and does not print it on the screen. Here is an example:

 <?php         $a = "Hans";         $result = sprintf ("This is the diary of %s.", $a);         echo "Result: $result<br>\n"; ?> 

This time the result is assigned to a variable called result and displayed on the screen using echo.

If you want a backslash to be put before every ., \\, +, *, ?, [, ^, ], (, $, or ), you can use the QuoteMeta function. Especially when building interfaces to other software products or when working with regular expressions, this function might be of interest for you because it helps you to escape special characters.

Here is an example of how the function can be used:

 <?php         $a = "Is 1+2*3=7?";         $result = QuoteMeta ($a);         echo "$result"; ?> 

The result will contain many backslashes:

 Is 1\+2\*3=7\? 

If you want to remove the backslashes inserted by QuoteMeta, you can use the stripslashes function.

strcmp can be used to compare strings and is another function that has been borrowed from C. The usage of strcmp in PHP is very similar to that of C, as you can see in the following example:

 <?php         $a = "abc";         $b = "bcd";         echo strcmp($a, $b)."<br>";         echo strcmp($b, $a)."<br>";         echo strcmp($a, $a)."<br>"; ?> 

In the first two lines variables are defined, which will be compared with each other in the next three lines. The first strcmp command returns -1 because the two variables are passed to the function in alphabetical order. The parameters are passed to the second command in reverse order, so 1 is returned. If both values are equal, strcmp will return 0. In the following lines, you can see the output of the script.

 -1 1 0 

The strlen function is widely used and can be taken to compute the length of a string. First, a string called $a is defined. In the next step, the length of this string is computed and displayed on the screen.

 <?php         $a = "This is a string";         echo strlen($a)."<br>\n"; 

?>$a

In some cases it might be useful to remove whitespace characters from the beginning and the end of a string. Therefore you can use trim:

 <?php         $b = "     I am a string     ";         echo 'beginning:'.trim($b).':end'; ?> 

$b contains a string with a few blanks at the beginning and the end of it. With the help of trim, these blanks can easily be removed:

 beginning:I am a string:end 

The result no longer contains these blanks. If you only want to remove the blanks on the left edge of the string, ltrim can be used. If the blanks on the right side have to be removed, rtrim will be the right function.

You can convert strings to uppercase letters and vice versa by using two easy-to-use PHP functions called strtoupper and strtolower. In the next example you will see how these functions can be used:

 <?php         $a = "i am a string";         $b = strtoupper($a);         echo "$b<br>\n";         echo strtolower($b); ?> 

First, a string is defined. In the next step it is converted to uppercase letters and assigned to $b. Finally both strings are displayed on the screen.

 I AM A STRING i am a string 

In many cases you don't want to convert all characters to upper- or lowercase letters. With the help of the ucfirst function, it is possible to convert only the first letter to uppercase. Ucwords makes sure that every word in a string starts with an uppercase letter:

 <?php         $a = "i am a string";         echo ucfirst($a)."<br>";         echo ucwords($a)."<br>"; ?> 

The output of the script is in no way surprising:

 I am a string I Am A String 

PHP supports a lot of functions related to strings and it is beyond the scope of this book to cover all of these functions in detail. We have to decided to mention only the most important and most widely used functions.

3.3.6 Working with One-Dimensional Arrays

The ability to handle arrays easily and efficiently is one of the features that has made PHP so successful in the past few years. Not only can arrays be handled easily, but many functions related to arrays are also available and you will learn about these functions in this section.

Arrays can either be one-dimensional or multidimensional. A one-dimensional array is a data structure used to store a list of values. You have already learned in the section "Data Types and Functions" earlier in this chapter that arrays are one of PHP'S built-in data types. However, arrays are in a way different than data types like integer or double. An array is not an atomic value, which means that it consists of one or more other values, which can be arrays again.

Let's start with an example where you will see how you can find out whether a variable is an array:

 <?php         $a = 12;         $b = array(23, "Hans", "Vienna", 1.78);         echo "a: ".is_array($a)."<br>";         echo "b: ".is_array($b); ?> 

You can see that an integer value and an array are defined. The array consists of one integer, two strings, and one floating-point value. As you can see, it makes absolutely no difference which values are inserted into an array because it is just a container for storing all kinds of variables. When executing the script, you can see that is_array returns 1 if the variable passed to it is an array:

 a: b: 1 

Now that you have learned to create arrays and to find out if a variable is an array, you will learn to access the components of an array. The first thing to know is to find out how many values are stored in an array. This can be done by using the count function. As soon as you know the number of components of your array, it is an easy task to display the content of the array on the screen:

 <?php         $a = array(23, "Hans", "Vienna", 1.78);         $vals = count($a);         echo "Number of values in the array: $vals<br><br>\n";         for     ($i = 0; $i < $vals; $i++)         {                 echo "Value number $i: $a[$i]<br>";         } ?> 

The output of the script shows that four records were found in the array. Finally all records are displayed on the screen. The various cells of the array are accessed by using parentheses and the index of the value:

 Number of values in the array: 4 Value number 0: 23 Value number 1: Hans Value number 2: Vienna Value number 3: 1.78 

Displaying all records on the screen can also be done differently:

 <?php         $a = array(23, "Hans", "Vienna", 1.78);         foreach ($a as $x)         {                 echo "$x<br>";         } ?> 

After defining the array, a loop is entered that is executed for every value in the array. Every value in $a is assigned to $x, which is displayed on the screen using an echo command:

 23 Hans Vienna 1.78 

An array does not have to be consecutively numbered. In many cases it is helpful to use strings to identify the values in an array:

 <?php         $a = array(age => 23, name => "Hans", residence => "Vienna",                 height => 1.78);         foreach ($a as $x)         {                 echo "$x<br>";         } ?> 

In the preceding example, an associative array is initialized and the content is displayed on the screen as shown in the next listing:

 23 Hans Vienna 1.78 

Many of you might have dealt with associative arrays already in Perl. In PHP things work pretty much the same way as in Perl. An associative array is just an array indexed with strings. The idea is to be able to store every data type in an array and to index it with anything you like.

Retrieving data from an associative array can be done as you have seen for arrays indexed with numbers:

 <?php         $a = array(age => 23, name => "Hans", residence => "Vienna",                 height => 1.78);         echo "Age: ".$a["age"]." years <br>";         echo "Name: ".$a["name"]."<br>";         echo "Residence: ".$a["residence"]."<br>";         echo "Height: ".$a["height"]." centimeter<br>"; ?> 

All values are displayed on the screen:

 Age: 23 years Name: Hans Residence: Vienna Height: 1.78 centimeter 

In this section we have already mentioned that an array can also contain arrays. The next example shows an array with one element containing an array with two elements:

 <?php         $a = array(name => array("Hans", "Epi"));         $b = $a["name"];         echo "$b[0] - $b[1]<br>\n"; ?> 

You can insert an array into an array just like any other record. The only thing you have to take care of is when retrieving the values again this is slightly more difficult than if it was just an ordinary value.

If you execute the script, the values you have inserted will be retrieved:

 Hans - Epi 

With the help of arrays, complex data structures can be built. However, if the data structures become very complex, it is useful to use object-oriented PHP instead of complex arrays and procedures. Object-oriented PHP will be covered extensively in the next chapter of this book.

An important command when working with arrays is the reset command. Unlike what some of you might expect, reset is not used to remove elements from an array but to set the pointer to the first element of an array. If you are working with an array, the pointer might not be on the first element and you will have trouble using commands like next and prev safely. In the next example you will see how to define an array, set the pointer to the first element, and display all records including the keys on the screen:

 <?php         $a = array(23, 16, 8, 99);         reset($a);         while (list ($key, $val) = each ($a))         {                 echo "$key: $val<br>\n";         } ?> 

As you can see, every value in the array has a key.

 0: 23 1: 16 2: 8 3: 99 

Finding the key of a value is an important task because the data structure can be indexed using any other variable.

Sorting data is another important operation:

 <?php         $a = array(23, 16, 8, 99);         sort($a);         foreach ($a as $val)         {                 echo "val: $val<br>\n";         } ?> 

For building efficient data structures, it is important to sort data before working with it. The output of the script you have just seen is displayed sorted because you have used sort to change the order of the elements.

 val: 8 val: 16 val: 23 val: 99 

To sort data in a reverse order, use arsort instead of sort:

 <?php         $a = array(23, 16, 8, 99);         arsort($a);         foreach ($a as $val)         {                 echo "val: $val<br>\n";         } ?> 

As you can see, the data is now displayed the other way around:

 val: 99 val: 23 val: 16 val: 8 

The opposite of sorting an array is to use shuffle a function for putting values in reverse order:

 <?php         $a = range(1, 7);         shuffle($a);         while (list ($key, $val) = each ($a))         {                 echo "$key: $val<br>\n";         } ?> 

First, you create an array that contains values from 1 to 7 using the range function. In the next step the array is shuffled and all values are displayed on the screen.

 0: 3 1: 1 2: 2 3: 4 4: 5 5: 7 6: 6 

The values are no longer ordered. Shuffling arrays can be useful for many purposes. Imagine a situation where you want to display records in a random order shuffle will solve the problem for you.

You have seen how an array can be accessed by using an index or a foreach command. Another way to process all values of an array is to use reset and next. Next sets the pointer to the next value in the array and returns the current value. With the help of a do/while loop, it is an easy task to go through the array:

 <?php         $a = array(23, 16, 8, 99);         reset($a);         $val = $a[0];         do         {                 echo "val: $val<br>\n";         }         while   ($val = next($a)); ?> 

As you can see following, all values are displayed on the screen:

 val: 23 val: 16 val: 8 val: 99 

Stacks are a special kind of array. They are a fundamental data structure and are heavily used by many programmers. If you want to process commands using postfix notation, stacks are an essential instrument. Two operations are defined for stacks: Push adds a value to the stack. Pop returns the last value that was added to the array and removes it from the list in other words stacks use a LIFO algorithm (LIFO = last in first out).

To make clear what you have just learned, we have included an example:

 <?php         $a = array();         array_push($a, 'the first value');         array_push($a, 'the second value');         array_push($a, 'the third value');         while (list ($key, $val) = each ($a))         {                 echo "$key: $val<br>\n";         }         echo "<br>removing: ".array_pop($a)."<br>";         echo "removing: ".array_pop($a)."<br><br>";         while (list ($key, $val) = each ($a))         {                 echo "$key: $val<br>\n";         } ?> 

In the first line, an empty array is defined. In the next three lines, values are added to the stack using array_push, and all values are displayed on the screen. Then two values are removed from the stack and displayed on the screen. As you can see, the return value of array_pop is returned and removed from the array. After adding three values to the array and removing two values from the array, one value is left and displayed on the screen:

 0: the first value 1: the second value 2: the third value removing: the third value removing: the second value 0: the first value 

Counting the values of an array can be done by using the array_count_values function. The idea of this function is to compute the frequency with which a value occurs in the array.

Sometimes it is necessary to remove duplicated values from an array. Array_unique will do the job for you:

 <?php         $a = array(23, 23, 12, 9, 23, 9);         $counted = array_count_values($a);         echo "Return data counted: <br>\n";         while (list ($key, $val) = each ($counted))         {                 echo "$key: $val<br>\n";         }         echo "<br>Return unique data: <br>\n";         $a = array_unique($a);         while (list ($key, $val) = each ($a))         {                 echo "$key: $val<br>\n";         } ?> 

After defining an array containing some value, an array is initialized containing the frequency with which various values in $a occur. In the first column the key is displayed. The second column tells us how often the key was found in the array.

In the next step the array_unique function is used to remove duplicated entries. The key to a value is the position in which a certain value has occurred in the original array. The value 9, for instance, was found on the fourth and the last position of the array. Because this is redundant, the last field in the array has been deleted and only the value in position number 4 remains:

 Return data counted: 23: 3 12: 1 9: 2 Return unique data: 0: 23 2: 12 3: 9 

The output of the function shows what comes out when the script is executed.

If you are working with more than just one array, it might happen that you have to compare arrays with each other. Therefore PHP provides some powerful and easy-to-use functions. One of the functions is called array_merge and is used to combine two arrays:

 <?php         $a = array(23, 12, 9);         $b = array(12, 13, 14);         $res = array_merge($a, $b);         while (list ($key, $val) = each ($res))         {                 echo "$key: $val<br>\n";         } ?> 

Two arrays are defined, which are merged. If you execute the script, the result will contain all values of both arrays as shown in the following listing:

 0: 23 1: 12 2: 9 3: 12 4: 13 5: 14 

The counterpart of array_merge is the array_diff function, which can be used to compute the difference of two arrays as shown following:

 <?php         $a = array(23, 12, 9);         $b = array(12, 13, 14);         $res = array_diff($a, $b);         while (list ($key, $val) = each ($res))         {                 echo "$key: $val<br>\n";         } ?> 

Two values can be found in $a that are not in $b:

 0: 23 2: 9 

If you want to compute the intersection of two arrays instead of the difference, you can use the array_intersect function. Just like array_diff and array_merge, array_intersect needs to have two arrays passed to it:

 <?php         $a = array(23, 12, 9);         $b = array(12, 13, 14);         $res = array_intersect($a, $b);         while (list ($key, $val) = each ($res))         {                 echo "$key: $val<br>\n";         } ?> 

One value is returned:

 1: 12 Calculating the sum of all values in an array can be done in many ways but the easiest one is to use array_sum: <?php         $a = array(23, 12, 9);         echo array_sum($a); ?> 

The resulting value 44 will be displayed on the screen.

Splitting a string and generating an array out of it is an important operation. If you have to process tab-separated files, for instance, splitting strings and generating arrays is an essential procedure. PHP provides a function called explode. Explode has to be called with two parameters. The first one tells PHP where to split the string by defining a pattern. The second parameter contains the variable you want to process.

The counterpart of explode is implode, which does exactly the opposite of explode:

 <?php         $a = "This is a string";         $b = explode(" ", $a);         while (list ($key, $val) = each ($b))         {                 echo "$key: $val<br>\n";         }         $c = implode(" ", $b);         echo "<br>$c<br>"; ?> 

At the beginning of the script, a variable is defined that is used to generate an array in the second line. A space character is selected as separator. In the next step the content of $b is displayed on the screen. Finally all values in $b are combined into a string again. Again a blank is chosen as the separator.

If you execute the script, the output will be displayed on the screen:

 0: This 1: is 2: a 3: string This is a string 

As you can see in the last line of the result, the array has been combined to the string you have defined in the first line again.

3.3.7 Working with Multidimensional Arrays

Multidimensional arrays are a little bit more difficult to handle than their one-dimensional counterparts. However, with some basic techniques, it is possible to perform complex operations.

Each can be used for processing one-dimensional or multidimensional arrays. Even for more complex data structures, each will play an important role:

 <?php         $a[0][0] = "Rock me Amadeus";         $a[0][1] = "Jeanny";         $a[0][2] = "Vienna Calling";         $a[1][0] = "Satellite to Satellite";         echo "<b>Falco's masterpieces:</b><br>\n";         while (list ($key, $val) = each ($a))         {                 echo "$key: $val<br>\n";         } ?> 

In the first four lines, a two-dimensional array is created and four values are assigned to it. The target is to display all records on the screen.

The next listing shows what comes out when you execute the script:

 Falco's masterpieces: 0: Array 1: Array 

The listing does not contain the desired result because each extracts a list of arrays instead of a list of single values from the multidimensional array. To display the data, you have to make some minor changes in the code:

 <?php         $a[0][0] = "Rock me Amadeus";         $a[0][1] = "Jeanny";         $a[0][2] = "Vienna Calling";         $a[1][0] = "Satellite to Satellite";         echo "<b>Falco's masterpieces:</b><br>\n";         while (list ($key, $val) = each ($a))         {                 while (list ($subkey, $subval) = each ($val))                 {                       echo "key:$key - subkey: $subkey - value: $subval<br>\n";                 }         } ?> 

A second loop has to be added to extract all fields from the arrays extracted from the multidimensional array. If you execute the script now, the result will contain all values:

 Falco's masterpieces: key:0 - subkey: 0 - value: Rock me Amadeus key:0 - subkey: 1 - value: Jeanny key:0 - subkey: 2 - value: Vienna Calling key:1 - subkey: 0 - value: Satellite to Satellite 

In the next step you want to sort the values in the array. To achieve that target, you can try to add a sort command after assigning the values to the array:

         sort($a); 

This won't lead to the desired result because PHP will sort the keys and not the values:

 Falco's masterpieces: key:0 - subkey: 0 - value: Satellite to Satellite key:1 - subkey: 0 - value: Rock me Amadeus key:1 - subkey: 1 - value: Jeanny key:1 - subkey: 2 - value: Vienna Calling 

If you want to sort the content of the array and not the keys, you have to build a multidimensional array where all axes have the same amount of values. In your case you can build a matrix with four values (2x2 matrix):

 $a[0][0] = "Rock me Amadeus"; $a[0][1] = "Jeanny"; $a[1][0] = "Vienna Calling"; $a[1][1] = "Satellite to Satellite"; 

This matrix can easily be sorted by using the array_multisort command:

 array_multisort($a[0], SORT_ASC, SORT_STRING,         $a[1], SORT_ASC, SORT_STRING); 

Both columns are sorted in ascending order. If you execute the script now, you will receive a sorted list:

 Falco's masterpieces: key:0 - subkey: 0 - value: Jeanny key:0 - subkey: 1 - value: Rock me Amadeus key:1 - subkey: 0 - value: Satellite to Satellite key:1 - subkey: 1 - value: Vienna Calling 

If you hadn't changed the data structure, you'd run into trouble because the size of the arrays would be inconsistent:

 Warning: Array sizes are inconsistent in /var/www/html/test/hello.php on line 8 

Array_multisort accepts two flags for influencing the way data is sorted. PHP supports two sorting order flags:

  • SORT_ASC Sort in ascending order

  • SORT_DESC Sort in descending order

In addition, three sorting type flags are provided:

  • SORT_REGULAR Compare items normally

  • SORT_NUMERIC Compare items numerically

  • SORT_STRING Compare items as strings

As you can see, array_multisort is a powerful and flexible function. However, it has to be used with care to make sure that the result of a sort process contains exactly the desired data.

You have already seen that a multidimensional array consists of many arrays that have one dimension less than the parent array. Knowing this will allow you to perform all operations you want to perform. Especially when working with multidimensional stacks, it is important to know what happens inside PHP and how data is stored by the interpreter.



PHP and PostgreSQL. Advanced Web Programming2002
PHP and PostgreSQL. Advanced Web Programming2002
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 201

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net