YOMEDIA
ADSENSE
PHP and MySQL by Example- P3
106
lượt xem 14
download
lượt xem 14
download
Download
Vui lòng tải xuống để xem tài liệu đầy đủ
Tham khảo tài liệu 'php and mysql by example- p3', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả
AMBIENT/
Chủ đề:
Bình luận(0) Đăng nhập để gửi bình luận!
Nội dung Text: PHP and MySQL by Example- P3
- constant to the following script that will define a COPY_RIGHT constant containing your SITE_NAME with the copyright symbol appended (concatenated) to it. Display the constants and their corresponding values in an HTML table. Hint: See http://www.desilva.biz/php/constants.html. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Chapter 5. Operators “Operator, give me the number for 911.” —Dan Castellaneta 5.1. About PHP Operators and Expressions Data objects can be manipulated in a number of ways by the large number of operators provided by PHP. Operators are symbols, such as +, -, =, >, and
- in. They tell PHP how to evaluate such an expression. Precedence refers to the way in which the operator binds to its operand; that is, should addition be done before division or should assignment come before multiplication. The precedence of one operator over another determines what operation is done first. As shown in the precedence table (see Table 5.1), the operators are organized as a hierarchy, with the operators of highest precedence at the top, similar to a social system where those with the most power (or money) are at the top. In the rules of precedence, the multiplication operator is of higher precedence than the addition operator, technically meaning the operator of higher precedence binds more tightly to its operands. The assignment operators are low in precedence and thus bind loosely to their operand. In the expression sum = 5 + 4, the equal sign is of low precedence so the expression 5 + 4 is evaluated first and then the result is assigned to sum. Parentheses are of the highest precedence. An expression placed within parentheses is evaluated first; for example, in the expression 2 * ( 10 - 4 ), the expression within the parentheses is evaluated first and that result is multiplied by 2. When parentheses are nested, the expression contained within the innermost set of parentheses is evaluated first. Table 5.1. Precedence and Associativity (Highest to Lowest) Operator Description Associativity () Parentheses Left to right[a] new Creates an object Nonassociative [ Array subscript Right to left ++ -- Auto increment, decrement Nonassociative ! ~ - Logical not, bitwise not, negation Nonassociative (int) (float) (string) (array) Cast (object) @ Inhibit errors * / % Multiply, divide, modulus Left to right + - . Add, subtract, string concatenation Left to right > Bitwise left shift, right shift Left to right < >= Greater than, greater than or equal to = = != Equal to, not equal to Nonassociative = = = != = Identical to (same type), not identical to & Bitwise AND Left to right ^ Bitwise XOR | Bitwise OR Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 5.1. Precedence and Associativity (Highest to Lowest) Operator Description Associativity && Logical and Left to right || Logical or Left to right ? : Ternary, conditional Left to right = += -= *= /= %= = Assignment Right to left and Logical AND Left to right xor Logical XOR Left to right or Logical OR Left to right , (comma) List separator, etc. Left to right [a] Not listed in the PHP manual, but seems to behave the same as in other languages. Associativity refers to the order in which an operator evaluates its operands: left to right, in no specified order, or right to left. When all of the operators in an expression are of equal precedence (see Table 5.1), normally the association is left to right; for example, in the expression 5 + 4 + 3, the evaluation is from left to right. In the following statement, how is the expression evaluated? Is addition, multiplication, or division done first? In what order, right to left or left to right? Example 5.1. Precedence and Associativity() Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Explanation 1 The order of associativity is from left to right. Multiplication and division are of a higher precedence than addition and subtraction, and addition and subtraction are of a higher precedence than assignment. To illustrate this, we’ll use parentheses to group the operands as they are grouped by PHP. In fact, if you want to force precedence, use the parentheses around the expression to group the operands in the way you want them evaluated. The following two examples produce the same result. var result = 5 + 4 * 12 / 4; could be written result = (5 + ( ( 4 * 12 ) / 4)); 2 In this example, the expressions enclosed within parentheses are evaluated first. The * and / are evaluated left to right because they are of the same precedence. Output of this example is shown in Figure 5.1. Figure 5.1. Output from Example 5.1. Table 5.1 summarizes the rules of precedence and associativity for the PHP operators. The operators on the same line are of equal precedence. The rows are in order of highest to lowest precedence. Example 5.2. Precedence and Associativity() Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Explanation 1 The variable, called $result, is assigned the result of the expression. $result = 5 + 4 * 12 / 4; produces: $result = 5 + 48 / 4 produces: $result = 5 + 12 and finally the sum: 17 Because multiplication and division are higher on the precedence table than addition, those expressions will be evaluated first, associating from left to right. 2 The result of the previous evaluation, the value of $result, is sent to the browser. 3 The expressions enclosed in parentheses are evaluated first and then multiplied. $result = ( 5 + 4 ) * ( 12 / 4 ); produces: 9 * 3 $result = 9 * 3 results in: 27 4 The result of the previous evaluation, the value of $result, is sent to the browser. See Figure 5.2. Figure 5.2. Output from Example 5.2. 5.1.3. Arithmetic Operators Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). See Table 5.2. Table 5.2. Arithmetic Operators Operator/Operands Function x + y Addition x – y Subtraction x * y Multiplication Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 5.2. Arithmetic Operators Operator/Operands Function x / y Division x % y Modulus Example 5.3. Arithmetic Operators Arithmetic operators 1 Explanation 1 This is the start of a PHP program. 2 Variables $num1 and $num2 are declared and assigned values 5 and 7, respectively. 3 The sum of $num1 and $num2 is assigned to $result and printed on line 3. 4 This arithmetic operation illustrates precedence and associativity. The expression in parentheses is evaluated first, then the module operator (the % sign) will divide that result by 7 and return the remainder, and addition is performed last. To show the order of evaluation, we can put parentheses around all of the expressions. Start evaluating with the innermost set of parentheses first (10/2 + 5), then the next set, and so on: (12 +( (10 / 2 + 5) %7)) See Figure 5.3 for output of this example. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Figure 5.3. Output from Example 5.3. 5.1.4. Short Circuit Assignment Operators The short circuit assignment operators allow you to perform an arithmetic or string operation by combining an assignment operator with an arithmetic or string operator. For example, $x = $x + 1 can be written $x+=1. Table 5.3. Assignment Operators Operator Example Meaning = $x = 5; Assign 5 to variable $x. += $x += 3; Add 3 to $x and assign result to $x. -= $x -= 2; Subtract 2 from $x and assign result to $x. *= $x *= 4; Multiply $x by 4 and assign result to $x. /= $x /= 2; Divide $x by 2 and assign result to $x. %= $x %= 2; Divide $x by 2 and assign remainder to $x. Example 5.4. Arithmetic Operators Shortcut Operators 1
- print "10 is assigned to \$num."; 3 $num += 2; print "\$num += 2; \$num is $num. "; 4 $num -= 1; print "\$num -= 1; \$num is $num. "; 5 $num *= 3; print "\$num *= 3; \$num is $num. "; 6 $num %= 5; print "\$num %= 5; \$num is $num."; ?> Explanation 1 The PHP program starts here. 2 10 is assigned to the variable $num. 3 The shortcut assignment operator, +=, adds 2 to the variable, $num. This is equivalent to: $num = $num + 1; 4 The shortcut assignment operator, -=, subtracts 1 from the variable, $num. This is equivalent to: $num = $num - 1; 5 The shortcut assignment operator, *, multiplies the variable $num by 3. This is equivalent to: $num = $num * 3; 6 The shortcut assignment modulus operator, %, yields the integer amount that remains after the scalar $num is divided by 5. The operator is called the modulus operator or remainder operator. The expression $num %=5 is equivalent to: $num = $num % 5;. See Figure 5.4 for output of this example. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Figure 5.4. Output from Example 5.4. 5.1.5. Autoincrement and Autodecrement Operators To make programs easier to read, to simplify typing, and, at the machine level, to produce more efficient code, the autoincrement (++) and autodecrement (--) operators are provided. The autoincrement operator performs the simple task of incrementing the value of its operand by 1, and the autodecrement operator decrements the value of its operand by 1. The operator has two forms: The first form prefixes the variable with either ++ or -- (e.g., ++$x or --$x); the second form postfixes (places the operator after) the variable name with either ++ or -- (e.g., $x++, x--). For simple operations, such as $x++ or $x--, ++$x or --$x, the effect is the same; both ++$x and $x++ add 1 to the value of $x, and both --$x and $x-- subtract one from the value of $x. See Table 5.4 for examples. Table 5.4. Autoincrement and Autodecrement Operators Operator Function What It Does Example ++$x Preincrement Adds 1 to $x $x = 3; $x++; $x is now 4 $x++ Postincrement Adds 1 to $x $x = 3; ++$x; $x is now 4 ––$x Predecrement Subtracts 1 from $x $x = 3; $x;–– $x is now 2 $x–– Postdecrement Subtracts 1 from $x $x = 3; --$x; $x is now 2 Now you have four ways to add 1 to the value of a variable: $x = $x + 1; $x += 1; $x++; ++$x ; You also have four ways to subtract 1 from the value of a variable: $x = $x - 1; $x -= 1; $x--; --$x; In Chapter 6, “Strings,” these operators are commonly used to increment or decrement loop counters. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- The Autoincrement/Autodecrement and Assignment The placement of the operators does make a difference in more complex expressions especially when part of an assignment; for example, $y = $x++ is not the same as $y = ++$x. See Figure 5.5. Figure 5.5. Start with: $y = 0; $x = 5;. See Example 5.5. Example 5.5. Autoincrement and Autodecrement Explanation 1 The variables, $x and $y, are initialized to 5 and 0, respectively. See Figure 5.5. 2 The preincrement operator is applied to $x. This means that $x will be incremented before the assignment is made. The value of $x was 5, now it is 6. The variable $y is assigned 6. $x is 6, $y is 6. 3 The new values of $y and $x are displayed in the browser window. 4 The variables, $x and $y, are assigned values of 5 and 0, respectively. 5 This time the postincrement operator is applied to $x. This means that $x will be incremented after the assignment is made. 5 is assigned to the variable $y, and then $x is incremented by 1. $x is 5, $y is 6. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- be incremented after the assignment is made. 5 is assigned to the variable $y, and then $x is incremented by 1. $x is 5, $y is 6. 6 The new values of $y and $x are displayed in the browser window. See Figure 5.6. Figure 5.6. Output from Example 5.5. 5.1.6. Some Useful Math Functions Table 5.5 lists some of the math functions provided by PHP. The complete list can be found at the PHP Web site. Table 5.5. Math Functions Function Meaning Example abs() Absolute value echo abs(-5); // 5 echo abs(5.3); // 5 base_convert() Convert a number echo base_convert("ff",16,10); // 255 echo base_convert("a",16,2); // 1010 between arbitrary echo base_convert(11,10,8); // 13 bases bindec() Binary to decimal echo bindec('1010'); // 10 echo bindec('110010'); // 50 ceil() Round fractions up echo ceil(6.2); // 7 echo ceil(6.8); // 7 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 5.5. Math Functions Function Meaning Example decbin() Decimal to binary echo decbin(5); // 101 echo decbin(20); // 10100 dechex() Decimal to echo dechex(15); // f echo dechex(124); // 7c hexadecimal decoct() Decimal to octal echo decoct(8); // 10 echo decoct(20); // 24 floor() Round fractions echo floor(6.2); // 6 echo floor(6.8); // 6 down getrandmax() Show largest echo getrandmax(); // returns 32767 possible random value hexdec() Hexadecimal to echo hexdec("ff"); // returns 255 echo hexdec("a"); // returns 10 decimal is_finite() Finds whether a echo is_finite(pi()); // returns 1 true value is a legal finite number, returns boolean is_infinite() Finds whether a echo is_infinite(pow(10, 1000000)); // returns 1 true value is infinite is_nan() Finds whether a echo is_nan(5.2) // returns false value is not a number max() Find highest value echo max(1,3,5,12,8); // 12 min() Find lowest value echo min(5,3.2, 8, 4); // 3.2 octdec() Octal to decimal echo octdec(10); // returns 8 pi() Get value of pi echo pi(); // 3.1415926535898 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Table 5.5. Math Functions Function Meaning Example pow() Exponential echo pow(3,2); // 9 echo pow(10,3); // 1000 expression rand(start,finish) Generate a random echo rand(1,10); // 5 echo rand(1,10); // 7 echo rand(1,10); // 10 integer between start and finish round() Rounds a float echo round(6.4); // 6 echo round(6.5); // 7 sqrt() Square root echo sqrt(81); // 9 srand() Seed the random number generator 5.1.7. Casting Operators As defined earlier, PHP is a loosely typed language, which really means that you don’t have to be concerned about what kind of data is stored in a variable. You can assign a number to $x on one line and on the next line assign a string to $x; you can compare numbers and strings, strings and booleans, and so on. PHP automatically converts values when it assigns values to a variable or evaluates an expression. If data types are mixed, that is, a number is compared to a string, a boolean is compared to a number, a string is compared to a boolean, PHP must decide how to handle the expression. Most of the time, letting PHP handle the data works fine, but there are times when you want to force a conversion of one type to another. This is done by using the casting operators listed in Table 5.6. Casting doesn’t change the value in a variable; it affects the way other operators interpret the value. Casting can be useful when casting strings to integers, arrays to objects, and so on. Table 5.6. Casting Operators Operator Synonym Changes Data Type To (int) (integer) Integer (float) (real) Floating point (string) String (bool) (boolean) Boolean (array) Array (see Chapter 8, “Arrays”) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- Format variable = (cast operator) value; Example: $salary = "52000"; // Variable is assigned a string value $salary = (float) $salary; // Value is forced to float and reassigned Example 5.6. Code View: Type Casting Explanation 1 The variable, $string, is assigned a string containing some leading numbers. 2 The new type is placed within parentheses, causing the variable, $string, to be temporarily cast from a string data type to an integer. The original $string will not be changed. It is still a string type, but $number will be an integer. PHP retains only the leading numbers in $string, thus removing dogs during the type cast. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- 3 ($total_seconds / 60) is cast to an integer before assigning the result to $minutes. See Figure 5.7 for output of this example. Figure 5.7. Type casting. Output from Example 5.6. 5.1.8. Concatention Operator Concatenation is from Late Latin concatenatio, from concatenare, “to chain together,” from Latin con-, “with, together” + catena, “a chain, a series.”[1] [1] http://dictionary.reference.com/search?r=10&q=concatenation The process of joining strings together is called concatenation. The PHP string concatenation operator is a dot (.). Its operands are two strings. It returns the concatenation of its right and left operands. If either operand is a number and the other is a string, PHP still concatenates them as strings. "pop" . "corn" // results in "popcorn" "Route " . 66 // results in "Route 66" There is also a shortcut concatenation assignment operator used like the shortcut operators (.=). Example 5.7. Concatenation
- echo "Second string: $string2"; echo "After concatenation: $string3"; echo "Whoops! Let's add a space: "; 3 $string3 = "$string1". " " . "$string2"; echo "After adding a space: $string3"; ?> Explanation 1 $string1 is assigned the string, "My dog"; $string2 is assigned the string, "has fleas". These two strings will be linked together with the concatenation operator. 2 $string3 is created by concatenating $string1 and $string2 together. The comment shows another way to use the concatenation operator: $string1.= $string2. When combined with the assignment operator, .=, $string1 will be assigned its value concatenated to the value of $string2, same as: $string1 = $string1 . $string2. 3 A space, represented as " ", is concatenated to $string1 to provide a space between $string1 and $string2. See Figure 5.8. Figure 5.8. Output from Example 5.7. 5.1.9. Comparison Operators When operands are compared, relational and equality operators are used. The operands can be numbers or strings. The result of the comparison is either true or false, a Boolean value. Comparisons are based on the type of the operands being compared. If, for example, two numbers are compared, the comparison is numeric, such as 5 > 4. When comparing two strings, they are compared letter by letter (lexographically) using ASCII values to represent the numeric Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- value of each letter; for example, "A" is less than "B" and when comparing "Daniel" to "Dan", "Daniel" is greater than "Dan". What if a string contains only numbers and is compared to another string that contains only numbers? Then the strings are converted to numbers and compared numerically. See Table 5.7 for examples. Table 5.7. Comparison Operators Operator/Operands Function $x == $y $x is equal to $y $x != $y $x is not equal to $y $x > $y $x is greater than $y $x >= $y $x is greater than or equal to $y $x < $y $x is less than $y $x
- Table 5.8. Equality Test with Strings and Numbers Test Are They Equal? -0 == +0 True false == false True true == 1 True null == "" True What Is Identical? The === and !== operators test that their operands are not only of the same value, but also of the same data type. String "54" is equal to number 54, but not identical because one is a string and the other is a number, even though their values are equal. See Table 5.9. Table 5.9. Identity Test with Strings and Numbers Test Are They Identical? "William" === "William" True "william" === "William" False 5 === 5.0 False "54" === 54 False null === null True -0 == +0 True false === false True true === 1 False null === "" False 5.1.10. Comparing Numbers When the comparison operators are used to compare numbers, numeric values are compared; for example, is 50 > 45? A boolean value of either true or false is returned. PHP compares its operands numerically if: 1. Both operands are numbers: 4 > 5 2. One operand is a number and the other is a string consisting of all numbers: "54" > 6 3. Both operands are strings containing all numbers: "56" < "57" For example: $x > $y $x is greater than $y $x >= $y $x is greater than or equal to $y Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
- $x > $y $x is greater than $y $x < $y $x is less than $y $x Explanation 1 The variables $x and $y are assigned values, to be compared later in the program. 2 If the value of $x is greater than the value of $y, a boolean value of either 1 or "" is returned and assigned to the variable result. 3 The boolean result of the comparison is displayed by the browser. It is true or 1; $x is greater than y. 4 If $x is less than $y, 1 is assigned to the variable, result; otherwise it is assigned the null string. 5 The boolean result of the comparison is displayed by the browser. It is cast to an integer so that you can see the value 0, representing false; $x is not greater than $y. See Figure 5.9. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
ADSENSE
CÓ THỂ BẠN MUỐN DOWNLOAD
Thêm tài liệu vào bộ sưu tập có sẵn:
Báo xấu
LAVA
AANETWORK
TRỢ GIÚP
HỖ TRỢ KHÁCH HÀNG
Chịu trách nhiệm nội dung:
Nguyễn Công Hà - Giám đốc Công ty TNHH TÀI LIỆU TRỰC TUYẾN VI NA
LIÊN HỆ
Địa chỉ: P402, 54A Nơ Trang Long, Phường 14, Q.Bình Thạnh, TP.HCM
Hotline: 093 303 0098
Email: support@tailieu.vn