# Professional PHP Programming phần 2

Chia sẻ: Hà Nguyễn Thúy Quỳnh | Ngày: | Loại File: PDF | Số trang:86

0
44
lượt xem
2

## Professional PHP Programming phần 2

Mô tả tài liệu

Một đoạn văn với một khởi đầu như thế này trong kịch bản Latin sẽ có một mức độ mặc định nhúng Level 0, và do đó hướng cơ bản của nó sẽ được trái sang phải.Các thuật toán bidi sử dụng tất cả các mã định dạng và mức độ nhúng để phân tích văn bản để quyết định làm thế nào nó phải được trả lại. Dưới đây là một thời gian ngắn

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: Professional PHP Programming phần 2

1. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com T o create this JavaScript code dynamically through PHP, we must be careful to escape the backslashes in PHP so that they are passed literally to the JavaScript. For example, consider what happens if we leave the backslashes unescaped: T his is what we would see if we "View Source" in the browser: T he newlines and tabs were interpreted by PHP instead of being passed as literal characters to JavaScript. This was not our intended effect. We want JavaScript to interpret these symbols as newlines and tabs, not PHP. The code below corrects this problem: TEAM FLY PRESENTS
2. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com B asically, we escape the \ n by typing \ \n . PHP will not interpret it as a newline, but rather as the literal characters \ a nd n . These will be passed on to the browser, where JavaScript will then interpret them as a newline. Similarly, the PHP code \ \t c auses \ t t o be passed to the browser, which is correctly interpreted as a tab by JavaScript. Summary I n the chapter, we learned how PHP interacts with the browser, how it receives HTML form data, and how it dynamically generates HTML documents. Upon submission, HTML form data are converted to name/value pairs and sent to the web server in a URL-encoded query string. URL encoding ensures that reserved characters are safely masked and that name/value pairs are represented in a standard way. PHP receives the data in the form of variables. URL encoding can also be used to pass variables from one PHP script to another. PHP provides three notations for comments: ❑ // Comment ❑ # Comment /* ❑ Comment */ T he first two of the comment types are used to comment single lines. The third type of comment code can be used to comment blocks of multiple lines. The backslash (\ ) is used to e scape a c haracter. Characters are often escaped to indicate a literal depiction of the character: e cho ("The variable \$applicant equals$applicant."); S ome escape sequences have special meanings, such as \ n (newline) and \t ( tab). TEAM FLY PRESENTS
3. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 4 1 Variables, Constants , and Data Types I n the previous chapter, we met PHP variables and saw briefly how to use them. We stated that PHP variables must begin with the dollar character ( $) and that PHP is a weakly-typed language – that is, variables can contain any type of data and do not have to be predefined as strings, integers, etc. We also saw how we can use PHP variables to extract data from an HTML form. In this chapter, we will look in more detail at variables and their data types. We will consider the issue of data type juggling in more detail, and we will look at some of the functions we can use to manipulate variables. We will also see how to assign a name to a constant value, which remains the same throughout the program. Data Types P HP has three basic data types: integer, double and string. There are also some not-so-basic types, namely arrays and objects, which are discussed in later chapters. Every variable has a specific type, though, as we’ve already mentioned, a variable’s type may change on the fly as the variable’s value changes, or as the code otherwise dictates. Integers use four bytes of memory and are used to represent ordinary, non-decimal numbers in the range of approximately –2 billion to +2 billion. Doubles, also known as float (floating-point) or real numbers, are used to represent numbers that contain a decimal value or an exponent. Strings are used to represent non- numeric values, like letters, punctuation marks, and even numerals. 2 // This is an integer 1 [JHS] I've added a bit of an introduction to avoid the abrupt start to the chapter. The chapter seems technically accurate, but I think we could do with a bit more explantion in places. The major topic which is omitted from this chapter is HTTP environment variables. We need a large section on these. While a complete listing should form an appendix, we need to show in this chapter how to access HTTP variables from PHP and to give a couple of practical examples: it would be good if these could be incorporated into the Job Application Form. TEAM FLY PRESENTS 4. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 2.0 // This is a double "2" // This is a string "2 hours" // This is another string M any languages contain a Boolean data type to represent the logical values T RUE a nd F ALSE . PHP does not. It instead uses expressions of the other three basic types that evaluate to either true or false values. Among integers, 0 (zero) evaluates as a false value, and any non-zero integer evaluates as a true value. Similarly, the double value 0 .0 ( or equivalents, such as 0 .000 ) evaluates to F ALSE , and any non-zero value evaluates to T RUE. Among strings, the empty string evaluates to F ALSE . It is represented as a pair of quotation marks containing nothing: " ". Any non-empty string evaluates to T RUE . Literals and Identifiers V ariables, constants, functions and classes must have distinct labels in order to be useful. Within these labels there is a distinction between literals and names. L iterals a re raw data, what you see is what you get. You can have number literals (e.g. 786) or string literals (e.g. "a quoted string"). Basically, you cannot make a literal mean something other than what it literally means. N ames , on the other hand, acquire their meaning by convention or by decree. The connection between a name and its meaning is arbitrary, a rose, as you know, "by any other name would smell as sweet". Names used in programming are called i dentifiers. Identifiers in PHP are case-sensitive, so$ price a nd $Price a re different variables. Built-in functions and structures are not case-sensitive, however; so e cho a nd E CHO d o the same thing. Identifiers may consist of any number of letters, digits, underscores, or dollar signs but cannot begin with a digit. Data Values I n addition to its meaning in the program, an identifier also has a value, which is a data item of a specific data type. If the identifier is able to change its value through the course of the program it is called a v ariable, whereas if the identifier has a fixed value, it is known as a c onstant . Constants C onstants a re values that never change. Common real-life constants include the value of pi (approx. 3.14), the freezing point of water under normal atmospheric pressure (0° C), and the value of "noon" (12:00). In terms of programming, there are two types of constants: literal and symbolic constants. Literal constants are simply unchanging values that are referred to directly, without using an identifier. W hen we use the term “constants”, we normally are referring to symbolic constants. Symbolic constants are a convenient way to assign a value once to an identifier and then refer to it by that identifier throughout your program. For example, the name of your company is a rather constant value. Rather than include the literal string " Phop's Bicycles " all throughout your application, you can define a constant called COMPANY w ith the value " Phop's Bicycles " and use this to refer to the company name throughout your code. Then, if the name ever does change as a result of a merger or a marketing ploy, there is only one place where you need to update your code: the point at which you defined the constant. Notice that constant names, unlike variable names, do not begin with a dollar sign. Defining Constants T he d efine() f unction is used to create constants: TEAM FLY PRESENTS 5. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com define("COMPANY", "Phop's Bicycles"); define("YELLOW", "#FFFF00"); define("VERSION", 3); define("NL", "\n"); I n the last example, we define a constant called N L t hat represents an HTML break tag followed by a newline character. Essentially, we have created a coding shortcut, since “\n ” is a commonly used combination. By convention, programmers define constants using all capital letters. A constant may contain any number or string value. Once constants are defined, they can be used in lieu of their values: echo("Employment at " . COMPANY . NL); T his is equivalent to: echo("Employment at Phop's Bicycles\n"); N otice that the constant appears outside of the quotation marks. The line: echo("Employment at COMPANY NL"); W ould literally print "Employment at COMPANY NL" to the browser. defined() T he d efined() f unction allows you to determine whether or not a constant exists. It returns 1 i f the constant exists and 0 i f it does not: if (defined("YELLOW")) { echo ("\n"); } Built-in Constants P HP includes several built-in constants. T RUE a nd F ALSE a re pre-defined with respective true (1) and false (0 or empty string) values. The constant P HP_VERSION i ndicates the version of the PHP parser that is currently running, such as 3 .0.11 . The constant P HP_OS indicates the server-side operating system on which the parser is running. echo(PHP_OS); // Prints "Linux" (for example) _ _FILE__ a nd _ _LINE__ hold the name of the script that is being parsed and the current line number within the script. (There are two underscore characters before and after the names of these constants.) PHP also includes a number of constants for error reporting: E _ERROR , E _WARNING , E _PARSE , and E _NOTICE . Furthermore, PHP utilizes a number of predefined variables that provide information about the environment on which PHP is running. A full list is included in Appendix ?. In order to view what these variables are set to on your computer, you can use the function p hpinfo() a s shown in the following code: TEAM FLY PRESENTS 6. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com T his should produce the page shown in the screenshot below: TEAM FLY PRESENTS 7. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Variable Declaration and Initialization D ifferent to constants, a variable is automatically declared in PHP when you assign a value to it. Assignment is accomplished with the assignment operator (= ). Note that the assignment operator (= ) and the equality operator ( == ) are different in PHP, as we shall see in the next chapter.$num_rows = 10; $product = "Tire Pump";$price = 22.00; $shipping = 5.00;$total = $price +$shipping; Type Juggling and Type Casting As mentioned previously, every PHP variable has a data type. That type is determined automatically by the value that is assigned to the variable. $a = 1; //$a is an integer $a = 1.2; // Now it's a double$a = "A"; // Now it's a string A s we’ll learn in the next few sections, there are also ways to explicitly specify the type of a variable. String Conversion and Type Juggling I f you perform a numerical operation on a string, PHP will evaluate the string as a number. This is known as s tring conversion , although the variable containing the string itself may not necessarily change. In the following example, $str i s assigned a string value:$str = "222B Baker Street"; I f we attempt to add the integer value 3 to $str ,$ str w ill be evaluated as the integer 222 for purposes of the calculation: $x = 3 +$str; // $x = 225; B ut the$ str variable itself has not changed: echo ($str); // Prints: "222B Baker Street" S tring conversion follows a couple of rules: Only the beginning of the string is evaluated as a number. If the string begins with a valid numerical ❑ value, the string will evaluate as that value; otherwise it will evaluate as zero. The string "3rd degree" would evaluate as 3 if used in a numerical operation, but the string "Catch 22" would evaluate as 0 (zero). TEAM FLY PRESENTS 8. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com A string will be evaluated as a double only if the double value being represented comprises the entire ❑ string. The strings "3.4", "-4.01", and "4.2e6" would evaluate as the doubles 3.4, -4.01, and 4.2000000. However if other non-double characters are included in the string, the string will evaluate as an integer: "3.4 children" would evaluate as the integer 3. The string "-4.01 degrees" would evaluate as the integer -4. In addition to string conversion, PHP performs type juggling between the two numeric types. If you perform a numerical operation between a double and an integer, the result will be a double:$a = 1; // $a is an integer$b = 1.0; // $b is a double$c = $a +$b; // $c is a double (value 2.0)$d = $c + "6th"; //$d is a doube (value 8.0) Type Casting Type casting allows you to explicitly change the data type of a variable: $a = 11.2; //$a is a double $a = (int)$a // Now it's an integer (value 11) $a = (double)$a // Now it's a double again (value 11.0) $b = (string)$a // $b is a string (value "11") ( array) a nd ( object) c asts are also allowed. ( integer) i s a synonym for ( int) . ( float) a nd ( real) a re synonyms for ( double) . Variable Variables P HP supports variable variables. Ordinary variables have dynamic values: you can set and change the variable's value. With variable variables, the name o f the variable is dynamic. Variable variables generally create more confusion than convenience (especially when used with arrays). They are included here for the sake of completeness; but in practice, they are of little real benefit. Here is an example of a variable variable:$field = "ProductID"; $$field = "432BB"; T he first line of the code above creates a string variable called  field a nd assigns it the value " ProductID" . The second line then uses the v alue o f the first variable to create the n ame o f the second variable. The second variable is named  ProductID a nd has the value " 432BB" . The following two lines of code produce the same output: echo (ProductID); // Prints: 432BB echo ($$field); // Prints: 432BB Useful Functions for Variables P HP has a number of built-in functions for working with variables. gettype() g ettype() determines the data type of a variable. It returns one of the following values: TEAM FLY PRESENTS
9. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com "integer" ❑ "double" ❑ "string" ❑ "array" ❑ "object" ❑ "class" ❑ "unknown type" ❑ We shall see more on arrays, objects and classes in later chapters. An example using g ettype() m ay be: if (gettype ($user_input) == "integer") {$age = $user_input; } R elated functions: i sset(), settype() settype() T he s ettype() f unction explicitly sets the type of a variable. The type is written as a string and may be one of the following: a rray , d ouble , i nteger , o bject o r s tring. If the type could not be set then a f alse v alue is returned.$a = 7.5; // $a is a double settype($a, "integer"); // Now it's an integer (value 7) s ettype() returns a t rue v alue if the conversion is successful. Otherwise it returns f alse . if (settype($a, "array")) { echo("Conversion succeeded."); } else { echo ("Conversion error."); } isset() and unset() u nset() i s used to destroy a variable, freeing all the memory that is associated with the variable so it is then available again. The i sset() f unction is used to determine whether a variable has been given a value. If a value has been set then it returns true .$ProductID = "432BB"; if (isset($ProductID)) { echo("This will print"); } unset($ProductID); if (isset ($ProductID)) { echo("This will NOT print"); } TEAM FLY PRESENTS 10. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com R elated functions: e mpty() empty() e mpty() i s nearly the opposite 2of i sset() . It returns t rue i f the variable is n ot s et, or has a value of zero or an empty string. Otherwise it returns f alse . echo empty($new); // true $new = 1; echo empty($new); // false $new = ""; echo empty($new); // true $new = 0; echo empty($new); // true $new = "Buon giorno"; echo empty($new); // false unset ($new); echo empty($new); // true The is...() functions T he functions i s_int() , is_integer() , and i s_long() a re all synonymous functions that determine whether a variable is an integer. i s_double() , i s_float() , and i s_real() d etermine whether a variable is a double. i s_string() , i s_array() , and i s_object() w ork similarly for their respective data types. $ProductID = "432BB"; if (is_string ($ProductID)) { echo ("String"); } The ...val() functions P HP provides yet another way to explicitly set the data type of a variable: the i ntval() , doubleval() , and s trval() f unctions. These functions cannot be used to convert arrays or objects. $ProductID = "432BB";$i = intval($ProductID); //$i = 432; T he i ntval() f unction can take an optional second argument representing the base to use for the conversion. By default, the function uses base 10 (decimal numbers). In the example below, we specify base 16 (hexadecimal numbers): 2 [kk] Empty() is NOT the opposite of isset() and this is important do know. Unlike Perl, PHP3 internally does not signal “undef” (undefined value) and “”/0 (zero value) in a different way and isset() is really the only way to determine this difference. That is why next(), prev() and the like are broken. TEAM FLY PRESENTS
11. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $ProductID = "432BB";$i = intval ($ProductID, 16); //$i = (decimal)275131 ; " 432BB" w as interpreted as a five-digit hexadecimal number. Building an Online Job Application Form T he sample application begun in the previous chapter illustrates how PHP variables are automatically created when HTML form data are submitted to a PHP script. Let's introduce a few more variables by adding more elements to the HTML form. Phop's Bicycles Job Application Are you looking for an exciting career in the world of cycling? Look no further! Please enter your name: Please enter your telephone number: Please enter your E-mail address: Please select the type of position in which you are interested: Accounting Bicycle repair Human resources Management Sales Please select the country in which you would like to work: Canada Costa Rica Germany United Kingdom United States Available immediately TEAM FLY PRESENTS
12. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com I n Chapter 3 it was demonstrated that for every element in a submitted HTML form, a PHP variable is created in the receiving script. Therefore, our script, " jobapp_action.php ", will have the following global variables available to it automatically: $applicant ,$ phone , $email ,$ position , $country ,$avail , and $enter . The value of these variables (except for$ enter ) will be determined by the user's input. What is the data type of these variables? To find out, we can use the g ettype() f unction in j obapp_action.php : I n so doing, we would discover that our script prints the word "string " every time, regardless of the value entered in the "applicant" text element. It even prints "string " if the form is submitted with no value entered. PHP automatically treats all submitted form data as strings. In most cases, this does not become an issue, even if your form data represent numeric values. PHP will perform string conversion and TEAM FLY PRESENTS
13. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com type juggling as needed for calculations. In the event that you find it necessary to explicitly set the type of data, however, you have the three 3different previously described techniques at your disposal: type casting, the s ettype() f unction, and the . ..val() f unctions. For a text element, a PHP variable will always be created when the form is submitted. If we leave the a pplicant t ext element blank and submit the form, a PHP variable called $applicant w ill be created in j obapp_action.php w ith the value "" ( empty string). Checkbox elements, such as a vail i n our example, do not behave like text elements. An$ avail v ariable will only be created if the checkbox was checked "on" when the form was submitted. If the checkbox is left unchecked, no variable will be created. We can use i sset() i n our j obapp_action.php s cript to determine whether or not the $avail v ariable exists, and therefore whether the a vail c heckbox element was checked: T he i sset() f unction will return either 1 o r 0 , and$ avail 's value will either be "on " or non-existent. It would be more convenient if $avail b ehaved like a Boolean variable and contained a value of 1 i f the checkbox was checked and 0 i f it was unchecked. This can be achieved easily enough by reassigning$ avail t o equal the output of the i sset() f unction: T his is a quick and easy way to convert "checkbox" variables into "boolean" variables. PHP does not actually contain a boolean data type. Instead it uses an integer with either a 0 (false) or non-zero (true) value. After the code above has executed, the line e cho (gettype($avail)); w ould reveal that it is now of type "integer". 3 [kk] four, neutral additions (+0, +0.0 or .””) are not in the online PHP3 manual, but they do work and they are a classic for this operation TEAM FLY PRESENTS 14. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Adding a Constant E arlier in this chapter, I demonstrated how to use a constant to store the name of the company. By storing this information in only one place, it is much easier to update the application if the name of the company changes, or if you want to use the same code for more than one company. In order to achieve this flexibility in our job application program, we need to make our HTML form dynamic by including PHP scripts in it. This means that we have to rename the file from "jobapp.html " to " jobapp.php ". Otherwise, PHP scripts will not be parsed by the web server. Once we have renamed the file, we can add our PHP tags that define and use the needed constant: 15. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com While this change does not affect the appearance or functionality of the application, it does make the code more manageable. In Chapter 6 "Statements", we will discuss how to use r equire() a nd i nclude() t o create a centralized script that can contain all of the constants needed by the entire application. For now, it is convenient enough just to define our constants near the top of the file that employs the constant. Summary I n this chapter we have looked in more detail at PHP variables and their data types. Constants and variables abstractly represent values. Constants are defined using the define() f unction. Once defined, a constant's value may not change. PHP has several built-in constants that contain information about the PHP script and its environment. The five data types in PHP are integer, double, string, array, and object. Boolean values are typically represented by zero or non-zero integers, though sometimes they are also represented by empty or non- empty strings. The type of a variable depends on the context in which it is used. PHP attempts to convert or juggle types as needed. To explicitly dictate a specific type, you can use casting, s ettype() , or the . ..val() f unctions. The i s...() f unctions can be used to determine a variable's current type. In the online job application form, we saw that the i sset() f unction can be very useful for converting HTML checkbox data into boolean variables. TEAM FLY PRESENTS 16. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 5 Operators An o perator i s used to determine a value by performing a procedure, or an o peration o n one or more other values. A value that is used in an operation is known as an operand . Addition is one of the simplest operations. In the expression 6 + 2 , 6 a nd 2 a re the operands, and the expression evaluates to 8 . Operators in PHP are mostly similar to those in C, Perl and related languages. This chapter describes them in detail. Arithmetic Operators L ike every programming language, PHP uses the basic mathematical operators: Operator Operation Performed Example Description Addition C alculates the sum of 7 and 2: 9 + 7+2 S ubtraction C alculates the difference when 2 is subtracted from 7: 5 - 7-2 M ultiplication C alculates the product of 7 and 2: 14 * 7*2 Division Calculates the dividend when 7 is divided by 2: 3.5 / 7/2 M odulus C alculates the remainder when 7 is divided by 2: 1 % 7%2 P HP generally ignores space characters. Although$ x = 6 * 2; a nd $x=6*2; a re equally legal in PHP, the former is far more readable, and therefore preferable. The Unary Operator T he minus sign ( - ) is also used with a single numeric value to negate a number (that is, to make a positive number negative, or a negative number positive). For example: TEAM FLY PRESENTS 17. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com$a = 2; $b = -$a; // $b = -2$c = -4; $d = -$c; // $d = 4 The Variable Assignment Operator A s we saw in Chapter 4, we use the assignment operator = t o set the values of variables: C omment: Check chapter ref. later.$x = 1; $y = x + 1;$length = $area /$width; $description = "Bicycle helmet"; The variable to the left of the = s ign is given the value of the expression to the right of the = . It is important not to confuse the assignment operator = w ith the comparison operator = = , which we will meet a little later in this chapter. Comparison Operators The comparison operators are used to test a condition. Expressions that use comparison operators will always evaluate to a Boolean value, i.e. either t rue o r f alse .$i = 5; if ($i < 6) echo ("This line will print."); // The expression '$i < 6' evaluates to 'true' if ($i > 6) echo ("This line will not print."); // The expression '$i > 6' evaluates to 'false' We will examine i f s tatements in greater detail in Chapter 6. The comparison operators are summarized in the table below: Operator Meaning Example Evaluates to true when: $h a nd$ i h ave equal E quals == $h ==$i values I s less than $h i s less than$ i < $h <$i I s greater than $h i s greater than$ i > $h >$i $h i s less than or equal to I s less than or equal to =$i TEAM FLY PRESENTS
18. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com to $i Does not equal$h d oes not equal $i !=$ h != $i Does not equal$h d oes not equal $i$ h $i A gain, remember that the comparison operator is the double equals sign (== ), the single equals sign (= ) representing the assignment operator. The assignment operator is used to set the value of a variable, whereas the comparison operator is used to determine or test the value of a variable. Failure to observe this distinction can lead to unexpected results. For example, we might write by mistake:$i = 4; if ($i = 7) echo ("seven"); // "seven" prints every time! T his is perfectly legal in PHP, so we won't get an error message. However, this i f s tatement does not test whether the value of$ i i s 7. Instead, it assigns the value 7 to $i , and then evaluates the value 7 , which is non-zero, and therefore t rue . Since no error is generated, this can be a difficult problem to detect. In general, if you encounter an if statement that always seems to evaluate to true , or always seems to evaluate to f alse , regardless of the condition, chances are good that you have accidentally used = i nstead of = =. In the code below, we have corrected the problem:$i = 4; if (7 == $i) echo ("seven"); // 7 ==$i evaluates to false, therefore the echo statement does not execute Here we have replaced the assignment operator with the equality comparison operator. In addition, we have placed the literal value on the left and the variable on the right. This habit makes it more difficult to make the same error in the future: if we mistakenly write 7 = $i , PHP will attempt to assign the value of the variable$ i t o the number 7 . This is clearly impossible, so an error will be generated: Note that type juggling and string conversion occur in comparisons; this means that if two variables (or literals) have the same value after type conversion, PHP will consider them to have identical values, even TEAM FLY PRESENTS
19. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com i f they have different data types. For example: echo ("7" == 7.00); This will print the number 1 , since the expression " 7" == 7.00 e valuates to t rue . In most real cases, this is not an issue. If, for some reason, you do need to make a distinction between a variable containing " 7" a nd one containing 7 .00 , you will have to compare both the values and the types of the variables: $a = "7";$b = 7.00; echo ($a ==$b); // Prints 1 (true) echo (($a ==$b) and (gettype ($a) == gettype ($b))); // Prints 0 (false) Logical Operators The logical operators are used to combine conditions, so that multiple conditions can be evaluated together as a single expression. 'Logical and' will return t rue o nly if all conditions are met; 'logical or' returns t rue when one or more of the conditions are met; and 'logical exclusive or' returns t rue i f one and only one of the conditions is met. The final logical operator, 'logical not' returns t rue i f the following expression evaluates to f alse . Example Operator Name Evaluates to true when: A nd Both $h a nd$i e valuate to true $h &&$i Or One or both of $h a nd$ i e valuate to t rue $h ||$i A nd Both $h a nd$i e valuate to true $h and$i Or Either $h i s true, or$ i i s true, or both $h or$i E xclusive Or One of $h a nd$ i e valuates to true, but not both $h xor$i N ot $h does not evaluate to t rue !$h N otice that there are two operators for "logical and" and two operators for "logical or". They behave similarly, but have different precedence. This means that they will be executed in a different order within an expression containing multiple operators; see the section on 'Operation Precedence and Associativity' below for more information. These examples should make the use of these operators a bit clearer. The results given are based on the following values: $h == 4 ;$i == 5 ; $j == 6 : if ($h == 4 && $i == 5 &&$j == 6) echo ("This will print."); I n this case, all the conditions are t rue, so the e cho f unction will be executed. if ($h == 3 or$i == 5) echo ("This will print."); Here, the first condition ( $h == 3 ) evaluates to f alse, and the second one ($i == 5 ) to t rue . TEAM FLY PRESENTS
20. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Because only one of the conditions linked by 'logical or' must be t rue, the whole expression evaluates to t rue . if ($h == 4 xor$i == 5 xor $j == 6) echo ("This will not print."); All the conditions in this expression evaluate to t rue . Because they are linked by x or, the expression itself is therefore f alse – x or e xpressions are t rue only when just one of the conditions within them is t rue . if !($h == 4 && $i == 5) echo ("This will not print."); T his example demonstrates the 'logical not' operator. The expression ($h == 4 && $i == 5) e valuates to t rue , so when negated with ! , the expression becomes f alse. This line also shows how parentheses can be used to link a number of sub-conditions to avoid errors due to precedence. One final example will show how useful this can be: if (($h == 4 || $i == 4) xor ($h == 5 || $j == 5) xor ($i == 6 || $j == 7)) echo ("This will print"); As you can see, conditional expressions can get quite complex, and brackets are very helpful in keeping track of exactly what conditions we want to link together. In this case, the bracketed conditions evaluate to t rue , f alse a nd f alse r espectively, so the entire expression is t rue – o nly of the xor 'd expressions being t rue . The String Concatenation Operator W e saw in Chapter 3 how the period (. ) is used in PHP as the concatenation operator to join two or more C omment: Check chapter ref string values into a single string. // The following code prints "Phineas Phop"$first = "Phineas"; $last = "Phop";$full = $first . " " .$last; // first name, plus a space, plus last name echo ($full); // The following code prints "Phop's Bicycles"$last = "Phop"; echo ($last . "'s Bicycles"); B e aware that the concatenation operator is not the only way to construct strings using variable data. As we saw in Chapter 3, PHP automatically interpolates string variables in string literals within double Comment: Check chapter ref q uotes. Therefore, both of the following lines will print Phineas Phop : echo ($first . " " . $last); // Using concatenation echo ("$first \$last"); // Using interpolation T he second line is marginally more efficient, both to type and to execute. Similarly, "Phop's Bicycles" can be printed using the line: TEAM FLY PRESENTS