fifteen years (15 Yrs) experience in various phase of System Development Life Cycle, specialized using COBOL either in mainframe or midrange platform, POWERBUILDER And Visual Basic/VBA/Net for object oriented programming. Working knowledge in Web development using ASP.NET, C#,JAVA, JAVASCRIPT, XML, HTML, and SHAREPOINT. Hands on IT experience in the following Industries Banking, Insurance, Manufacturing, Government, Retailing Business, and Telecommunication.
the PHP language, as well as a full coverage of the PHP Syntax You will be exposed to examples of building web pages that incorporates PHP as it’s primary building blocks. that incorporates PHP as it’s primary building blocks.
the Web, is your tool for creating dynamic Web pages. Rich in features that make Web design and programming easier, PHP is in use on over 13 million domains (according to the Netcraft survey at www.php.net/usage.php). Its popularity continues to grow, meaning that it must be fulfilling its function pretty well. PHP stands for PHP: HyperText Preprocessor. In its early development by a guy named Rasmus Lerdorf, it was called Personal Home Page tools. When it developed into a full-blown language, the name was changed to be more in line with its expanded functionality. The PHP language’s syntax is similar to the syntax of C, so if you have experience with C, you’ll be comfortable with PHP. PHP is actually simpler than C because it doesn’t use some of the more difficult concepts of C. PHP also doesn’t include the low-level programming capabilities of C because PHP is designed to program Web sites and doesn’t require those capabilities.
Lerdorf in June 1995, to make various common web programming tasks easier and less repetitive. The name originally stood for "Personal Home Page," but has since become a recursive acronym, standing for "PHP: Hypertext Preprocessor." The goal of that release was to minimize the amount of code required to achieve results, which led to PHP being HTML-centricthat is, PHP code was embedded inside HTML. The second PHP release, known as PHP/FI 2.0, was the first to achieve widespread popularity, and despite the parsing inconsistencies, it managed to attract a few converts. The release of PHP 3 was largely driven by Zeev Suraski and Andi Gutmans, who rewrote PHP from the ground up and removed the parsing problems. PHP 3 also rewrote PHP from the ground up and removed the parsing problems. PHP 3 also made it much easier for others to extend the languageparticularly keen developers could now easily write their own modules for the language, adding functionality at the core level. With PHP 3, the language had also gained limited object-oriented support, and this added extra fuel to the fire of PHP's growth. By the time PHP 3 was replaced in the middle of 2000, it was installed on over 2.5 million web site domains, as compared to 250,000 just 18 months before. Its successor, PHP 4, contained numerous major changes, including the switch to what is called the Zend Engine .
Gutmans to promote PHP in the corporate environment, and the engine they produced brought with it numerous advantages. By taking over the core of PHP, the Zend Engine introduced reference counting to ensure there were no memory leaks; introduced web server abstraction so that PHP ran on Apache 1.3.x, Apache 2, Microsoft's IIS, Zeus, AOLServer, and more; and also changed the way that PHP code was executed so that code was read once, converted to an internal format, then executed. This new execution paradigm allowed the use of external code caches, also known as PHP accelerators, that further boost performance. Although not as vast as the jump from PHP 3 to PHP 4, the move from PHP 4 to PHP 5 is still a big one. Along with hugely improved object orientation, the addition of try/catch error handling, and exceptions, there are two major new extensions: SimpleXML, a fast and easy-to-learn way to interact with XML documents, and SQLite, a new flat-file database API that eases the burden of deploying simple database solutions.
because of its many advantages: It’s fast. Because it is embedded in HTML code, the response time is short. It’s inexpensive — free, in fact. PHP is proof that free lunches do exist and that you can get more than you paid for. It’s easy to use. PHP contains many special features and functions needed to create dynamic Web pages. The PHP language is designed to be included easily in an HTML file. It can run on many operating systems. It runs on a wide variety of It can run on many operating systems. It runs on a wide variety of operating systems — Windows, Linux, Mac OS, and most varieties of Unix. Technical support is widely available. A large base of users provides free support via e-mail discussion lists. It’s secure. The user does not see the PHP code. It’s designed to support databases. PHP includes functionality designed to interact with specific databases. It relieves you of the need to know the technical details required to communicate with a database. It’s customizable. The open source license allows programmers to modify the PHP software, adding or modifying features as needed to fit their own specific environments.
the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other. Case Sensitivity The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo, while, class, etc., are case-insensitive. Thus, these and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent: echo("hello, world"); ECHO("hello, world"); EcHo("hello, world"); Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different variables.
PHP code that does something. It can be as simple as a variable assignment or as complicated as a loop with multiple exit points. Here is a small sample of PHP statements, including function calls, assignment, and an if test: echo "Hello, world"; myfunc(42, "O'Reilly"); $a = 1; $name = "Elphaba"; $b = $a / 25.0; if ($a == $b) { echo "Rhyme? And Reason?"; } if ($a == $b) { echo "Rhyme? And Reason?"; } PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages, in PHP the semicolon before the closing brace is not optional: if ($needed) { echo "We must have it!"; // semicolon required here } // no semicolon required here after the brace The semicolon is optional before a closing PHP tag:
a PHP program. You can spread a statement across any number of lines, or lump a bunch of statements together on a single line. For example, this statement: raise_prices($inventory, $inflation, $cost_of_living, $greed); could just as well be written with more whitespace: raise_prices( $inventory, $inflation, $cost_of_living, $cost_of_living, $greed); You can take advantage of this flexible formatting to make your code more readable (by lining up assignments, indenting, etc.). Some lazy programmers take advantage of this free-form formatting and create completely unreadable codethis isn't recommended.
but they are ignored by PHP. Even if you think you're the only person who will ever read your code, it's a good idea to include comments in your codein retrospect, code you wrote months ago can easily look as though a stranger wrote it. A good practice is to make your comments sparse enough not to get in the way of the code itself but plentiful enough that you can use the comments to tell what's happening. Don't comment obvious things, comments to tell what's happening. Don't comment obvious things, lest you bury the comments that describe tricky things. For example, this is worthless: $x = 17; // store 17 into the variable $x whereas this will help whoever maintains your code: // convert &#nnn; entities into characters $text = preg_replace('/&#([0-9])+;/e', "chr('\\1')", $text); code development under JavaScript.
are used to name variables, functions , constants, and classes. The first character of an identifier must be either an ASCII letter (uppercase or lowercase), the underscore character (_), or any of the characters between ASCII 0x7F and ASCII 0xFF. After the initial character, these characters and the digits 0-9 are valid. Variable names Variable names always begin with a dollar sign ($) and are case- Variable names always begin with a dollar sign ($) and are case- sensitive. Here are some valid variable names : $bill $head_count $MaximumForce $I_HEART_PHP $_underscore $_int
These variables are all different: $hot_stuff $Hot_stuff $hot_Stuff $HOT_STUFF Function names Function names Function names are not case-sensitive. Here are some valid function names: Tally list_all_users deleteTclFiles LOWERCASE_IS_FOR_WIMPS _hide These function names refer to the same function: howdy HoWdY HOWDY HOWdy howdy
only scalar valuesBoolean, integer, double, and stringcan be constants . Once set, the value of a constant cannot change. Constants are referred to by their identifiers and are set using the define( ) function: define('PUBLISHER', "O'Reilly & Associates"); echo PUBLISHER;
decimal integer, a decimal point, another decimal integer, an exponent, and a type suffix. The exponent is specified by using an e or E followed by an integer that can be signed by proceeding it with a - or a +. A floating- point literal should have at least one digit plus either a decimal point or e or E. For example 4.25 (floating point literals) .4e3 2E-8 -6.2e9 A Boolean literal is specified by one of two values: true or false. Finally, string literals are specified by using zero or more characters Finally, string literals are specified by using zero or more characters enclosed in double or single quotes. For example “banana” (string literals) ‘pear’ “goodbye \t forever”
endif endif include() include() require_once() require_once() _ _FILE_ _ _ _FILE_ _ Const Const endswitch endswitch Include_once() Include_once() return return _ _FUNCTION_ _ _ _FUNCTION_ _ Continue Continue endwhile endwhile interface interface static static _ _LINE_ _ _ _LINE_ _ Declare Declare eval() eval() isset() isset() switch switch _ _METHOD_ _ _ _METHOD_ _ Default Default exception exception list() list() throw throw Abstract Abstract die() die() exit() exit() new new try try Abstract Abstract die() die() exit() exit() new new try try And And Do Do extends extends old_function old_function unset() unset() array() array() echo() echo() final final Or Or use use As As Else Else for for php_user_filter php_user_filter var var Break Break elseif elseif foreach foreach print() print() while while Case Case empty() empty() function function private private xor xor catch catch enddeclare enddeclare global global protected protected cfunction cfunction endfor endfor if if public public Class Class endforeach endforeach implements implements require() require()
as a double quote rather than treating it Print the next character as a double quote rather than treating it as a string terminator as a string terminator \ \’ ’ Print the next character as a single quote rather than treating it Print the next character as a single quote rather than treating it as a string terminator as a string terminator \ \n n Print a new line character Print a new line character \ \t t Print a tab character Print a tab character \ \r r Print a carriage return (used primarily on Windows) Print a carriage return (used primarily on Windows) \ \$ $ Print the next character as a dollar rather than treating it as part Print the next character as a dollar rather than treating it as part \ \$ $ Print the next character as a dollar rather than treating it as part Print the next character as a dollar rather than treating it as part of a variable name of a variable name \ \\ \ Print the next character as a backslash rather than treating it as Print the next character as a backslash rather than treating it as an escape character an escape character Here is a code example of these escape sequences in action: <?php $MyString = "This is an \"escaped\" string"; $MySingleString = 'This \'will\' work'; $MyNonVariable = "I have \$zilch in my pocket"; $MyNewline = "This ends with a line return\n"; $MyFile = "c:\\windows\\system32\\myfile.txt"; ?>
types. Four are scalar (single-value) types: integers , floating-point numbers, strings, and Booleans. Two are compound (collection) types: arrays and objects. The remaining two are special types: resource and NULL. Integers Most people specify their numbers using base 10, meaning that the digits 0 to 9 are used. However, you may also specify them in hexadecimal (base 16) or octal (base 8). The octal number system only uses the digits 0 to 7. For example, the (base 8). The octal number system only uses the digits 0 to 7. For example, the decimal number 3291 represented in octal is 6333. Represented in hexadecimal, which uses 0 to 9, then A, B, C, D, E, and F. Decimal values are represented by a sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (–) sign. If there is no sign, positive is assumed. Examples of decimal integers include the following: 1998 -641 +33
of digits from 0 to 7. Like decimal numbers, octal numbers can be prefixed with a plus or minus. Here are some example octal values and their equivalent decimal values: 0755 // decimal 493 +010 // decimal 8 Hexadecimal values begin with 0x, followed by a sequence of digits (0–9) or letters (A–F). The letters can be upper- or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign in hexadecimal numbers: 0xFF // decimal 255 0x10 // decimal 16 0x10 // decimal 16 -0xDAD1 // decimal -56017 If you try to store a too-large integer in a variable, it will automatically be turned into a floating-point number. Use the is_int( ) function (or its is_integer( ) alias) to test whether a value is an integer: if (is_int($x)) { // $x is an integer }
else you will need floating-point numbers, often called real numbers or just floats. These are numbers like 1.1, 1.1111112, -12345678.9123, and even 1.0. You may also specify an exponent with your float, i.e., 3.14159e4 is equal to 31415.9. You may not specify your floats using anything but decimal, so -0x4.AF will generate an error. Unlike Perl, there is no thousands separator in PHP, so values such as 1_221_279 will not work. Here are some examples of floating-point arithmetic: $a = 1.132324; $b = $a + 1; $b = $a + 1.0; $c = 1.1e15; $d = (0.1+0.7) * 10; Mixing a float with an integer, as in line two, results in another float so that PHP doesn't lose any accuracy. Line four specifies a very large exponent; if you print out the resulting number, you will actually get 1.1E+015 back because the number is so large.
includes core- level support for creating and manipulating strings. A string is a sequence of characters of arbitrary length. String literals are delimited by either single or double quotes: 'big dog' "fat hog“ Variables are expanded within double quotes, while within single quotes Variables are expanded within double quotes, while within single quotes they are not: $name = "Guido"; echo "Hi, $name\n"; echo 'Hi, $name'; Output would be Hi, Guido Hi, $name
that a given variable can change its type as needed), it will automatically convert one type of variable to another whenever possible. Most data types are freely convertible to most other data types; this code illustrates that point: $mystring = "12"; $myinteger = 20; print $mystring + $myinteger; That script will output 32, despite the fact that one of the variables is a string and the other is an integer. PHP will convert the non-integer operand, $mystring, into an integer, and will find that it is, in fact, an integer inside a string. If PHP converts a string such as "wombat" to an integer, it becomes 0.
something is true or not. Like most programming languages, PHP defines some values as true and others as false. Truth and falseness determine the outcome of conditional code such as: if ($alive) { ... } In PHP, the following values are false: • The keyword false • The keyword false • The integer 0 • The floating-point value 0.0 • The empty string ("") and the string "0" • An array with zero elements • An object with no values or functions • The NULL value
resource values (which are described later, in the “Resources” section). PHP provides true and false keywords for clarity: $x = 5; // $x has a true value $x = true; // clearer way to write it $y = ""; // $y has a false value $y = false; // clearer way to write it Use the is_bool( ) function to test whether a value is a boolean: if (is_bool($x)) { // $x is a boolean }
can identify by position (a number, with zero being the first position) or some identifying name (a string): $person[0] = "Edison"; $person[1] = "Wankel"; $person[2] = "Crapper"; $creator['Light bulb'] = "Edison"; $creator['Light bulb'] = "Edison"; $creator['Rotary Engine'] = "Wankel"; $creator['Toilet'] = "Crapper"; The array( ) construct creates an array: $person = array('Edison', 'Wankel', 'Crapper'); $creator = array('Light bulb' => 'Edison', 'Rotary Engine' => 'Wankel', 'Toilet' => 'Crapper');
} foreach ($creator as $invention => $inventor) { echo "$inventor created the $invention<br>"; } } Hello, Edison Hello, Wankel Hello, Crapper Edison created the Light bulb Wankel created the Rotary Engine Crapper created the Toilet
various sort functions: sort($person); // $person is now array('Crapper', 'Edison', 'Wankel') asort($creator); // $creator is now array('Toilet' => 'Crapper', // 'Light bulb' => 'Edison', // 'Rotary Engine' => 'Wankel'); Use the is_array( ) function to test whether a value is an array: if (is_array($x)) { // $x is an array }
That value is available through the case-insensitive keyword NULL. The NULL value represents a variable that has no value $aleph = "beta"; $aleph = null; // variable's value is gone $aleph = Null; // same $aleph = NULL; // same Use the is_null( ) function to test whether a value is NULL—for instance, to see whether a variable has a value: if (is_null($x)) { // $x is NULL }
. . Concatenation Concatenation Returns the second value Returns the second value appended to the first: $a . $b appended to the first: $a . $b .= .= Shorthand concatenation Shorthand concatenation Appends the second value to Appends the second value to the first: $a .= $b the first: $a .= $b These operators are used to join strings together, like this: These operators are used to join strings together, like this: $first = "Hello, "; $second = "world!"; // join $first and $second; assign to $third $third = $first . $second; // $third is now "Hello, world!“ $first .= " officer!"; // $first is now "Hello, officer!"
you may need to use a comparison of two values to continue or to terminate your loop or condition. In PHP, when performing a comparison, you must use a comparison operator between the two values you are comparing. What you get in return is a Boolean value representing the outcome of the comparison. Operator Operator Result Result Equal (==) Equal (==) Returns true if the operands are equal Returns true if the operands are equal Identical (===) Identical (===) Returns true if the operands are equal and of the Returns true if the operands are equal and of the same type same type Not equal (!=) <> Not equal (!=) <> Returns true if the operands are not equal Returns true if the operands are not equal Not equal (!=) <> Not equal (!=) <> Returns true if the operands are not equal Returns true if the operands are not equal Not identical (!==) Not identical (!==) Returns true if the operands are not equal or not of Returns true if the operands are not equal or not of the same type the same type Greater than (>) Greater than (>) Returns true if the left operand is greater than the Returns true if the left operand is greater than the right operand right operand Less than (<) Less than (<) Returns true if the right operand is greater then Returns true if the right operand is greater then the left operand the left operand Less than or equal Less than or equal to (<=) to (<=) Returns true if the left operand is less than or Returns true if the left operand is less than or equal to the right operand equal to the right operand Greater than or Greater than or equal to (>=) equal to (>=) Returns true if the left operand is greater than or Returns true if the left operand is greater than or equal to the right operand equal to the right operand
++$a ++$a Pre Pre- -increment increment Increments $a by one, then Increments $a by one, then returns $a returns $a $a++ $a++ Post Post- -increment increment Returns $a, then increments $a Returns $a, then increments $a by one by one $a $a-- -- Post Post- -decrement decrement Returns $a, then decrements $a Returns $a, then decrements $a by one by one by one by one $a $a Pre Pre- -increment increment Decrements $a by one, then Decrements $a by one, then returns $a returns $a
before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 Follows PEMDAS Follows PEMDAS Parentheses, Exponents, Multiplication, Division, Addition, Subtraction
are occasions when it’s useful to consider a value as a specific type. The casting operators, (int), (float), (string), (bool), (array), and (object), allow you to force a value into a particular type. To use a casting operator, put the operator to the left of the operand. Operator Operator Changes Type To Changes Type To Example Example (int) (int) integer integer $a = "5"; $b = (int) $a; $b = (int) $a; (float) (float) float float $a = 5; $b = (float) $a; (string) (string) String String $a = 5; $b = (string) $a; (bool) (bool) Boolean Boolean (array) (array) Array Array (object) (object) Object Object
and return a values based on the two tested. Operator Operator Function Performed Function Performed Example Example && && True if both $a and $b True if both $a and $b are true are true expr1 && expr2 expr1 && expr2 AND AND True if both $a and $b True if both $a and $b are true are true expr1 AND expr2 expr1 AND expr2 are true are true || || True if either $a or $b is True if either $a or $b is true true expr1 || expr2 expr1 || expr2 OR OR True if either $a or $b is True if either $a or $b is true true expr1 OR expr2 expr1 OR expr2 XOR XOR True if either $a or $b is True if either $a or $b is true, but not both true, but not both expr1 XOR expr2 expr1 XOR expr2 ! ! Inverts true to false Inverts true to false and false to true: !$a and false to true: !$a !expr !expr
for a great variety of tasks to be performed in your application. Using any of PHP looping statements, you can repeat a series of statements until a certain condition is met. Additionally, with conditional statements, you can limit the execution of PHP code based on a certain criteria, or update information based on yet another criteria.
enables you to test a condition and if it is true, execute a block of code. Optionally you can execute a block of code if the statement evaluates to false. This is done using the else statement. The if ...else statement may be nested. Following is the syntax for the if...else statement: Syntax if (expression) statement statement if (expression) statement else statement
To include more than one statement in an if statement, use a block —a curly brace-enclosed set of statements: if ($user_validated) { if ($user_validated) { echo 'Welcome!"; $greeted = 1; } else { echo "Access Forbidden!"; exit; }
Instead of enclosing the block of statements in curly braces, end the if line with a colon (:) and use a specific keyword to end the block (endif, in this case). For example: if ($user_validated) : echo "Welcome!"; $greeted = 1; else : echo "Access Forbidden!"; exit; endif; Because if is a statement, you can chain them: if ($good) print('Dandy!'); else if ($error) print('Oh, no!'); else print("I'm ambivalent...");
provides an easier syntax: the elseif statement. For example, the previous code can be rewritten as: if ($good) print('Dandy!'); elseif ($error) print('Oh, no!'); else print("I'm ambivalent..."); The ternary conditional operator (?:) can be used to shorten simple true/false tests. Take a common situation such as checking to see if a given variable is true and printing something if it common situation such as checking to see if a given variable is true and printing something if it is. With a normal if/else statement, it looks like this: <td><? if($active) echo 'yes'; else echo 'no'; ?></td> With the ternary conditional operator, it looks like this: <? echo '<td>'.($active ? 'yes':'no').'</td>' ?> Compare the syntax of the two: if (expression) true_statement else false_statement (expression) ? true_expression : false_expression
expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. The program first looks for a label matching the value of expression and then executes the associated statement. If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement. If no default statement is found, the program continues execution at the statement following the end of switch. switch. The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.
: statement; break; } } Arguments expression is the value matched against label. label is an identifier used to match against expression. statement is any statement.
'ktatroe') // do something elseif ($name == 'rasmus') // do something elseif ($name == 'ricm') // do something elseif ($name == 'bobk') // do something You can replace that statement with the following switch statement: switch($name) { case 'ktatroe': case 'ktatroe': // do something break; case 'rasmus': // do something break; case 'ricm': // do something break; case 'bobk': // do something break; }
do something break; case 'rasmus': // do something break; case 'ricm': // do something break; case 'bobk': // do something break; endswitch; endswitch; Because statements are executed from the matching case label to the next break keyword, you can combine several cases in a fall-through. In the following example, "yes" is printed when $name is equal to "sylvie" or to "bruno": switch ($name) { case 'sylvie': // fall-through case 'bruno': print('yes'); break; default: print('no'); break; }
loop in PHP that can initialize a statement, update an expression, and loop until a condition is met. This statement consists of three optional expressions. These expressions are all enclosed in a single set of parenthesis and are separated by a semicolon (;). Following the for loop statement is a block of code to be executed in the loop. The syntax for a for loop follows: The structure of a for statement is: for (start; condition; increment) statement statement for ($counter = 0; $counter < 10; $counter++) echo "Counter is $counter\n"; The expression start is evaluated once, at the beginning of the for statement. Each time through the loop, the expression condition is tested. If it is true, the body of the loop is executed; if it is false, the loop ends. The expression increment is evaluated after the loop body runs.
in an array. To loop over an array, accessing each key, use: foreach ($array as $current) { // ... } The alternate syntax is: foreach ($array as $current): // ... endforeach; To loop over an array, accessing both key and value, use: foreach ($array as $key => $value) { // ... } The alternate syntax is: foreach ($array as $key => $value): // ... endforeach;
array is to use the foreach construct: $addresses = array('spam@cyberpromo.net', 'abuse@example.com'); foreach ($addresses as $value) { echo "Processing $value\n"; } Processing spam@cyberpromo.net Processing abuse@example.com PHP executes the body of the loop (the echo statement) once for each element of $addresses in turn, with $value set to the current element. Elements are processed by their internal order. An alternative form of foreach gives you access to the current key: An alternative form of foreach gives you access to the current key: $person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma'); foreach ($person as $k => $v) { echo "Fred's $k is $v\n"; } Fred's name is Fred Fred's age is 35 Fred's wife is Wilma In this case, the key for each element is placed in $k and the corresponding value is placed in $v. The foreach construct does not operate on the array itself, but rather on a copy of it. You can insert or delete elements in the body of a foreach loop, safe in the knowledge that the loop won't attempt to process the deleted or inserted elements.
while statement will keep executing a block of code it contains until the condition it is testing is false. Following is the syntax for the while statement: while (condition) { statements } As an example, here's some code that adds the whole numbers from 1 to 10: $total = 0; $i = 1; while ($i <= 10) { $total += $i; } } The alternative syntax for while has this structure: while (expr): statement; ...; endwhile; For example: $total = 0; $i = 1; while ($i <= 10): $total += $i; endwhile;
the loop and continues executing the code following the terminated loop. You can prematurely exit a loop with the break keyword. In the following code, $i never reaches a value of 6, because the loop is stopped once it reaches 5: $total = 0; $i = 1; while ($i <= 10) { while ($i <= 10) { if ($i == 5) break; // breaks out of the loop $total += $i; $i++; }
indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop. For example: $i = 0; while ($i < 10) { while ($j < 10) { if ($j == 5) break 2; // breaks out of two while loops break 2; // breaks out of two while loops $j++; } $i++; } echo $i; echo $j; Output 0 5
in a loop and continues the loop with the next iteration. The continue statement skips ahead to the next test of the loop condition. As with the break keyword, you can continue through an optional number of levels of loop structure: while ($i < 10) { while ($j < 10) { if ($j = 5) continue 2; // continues through two levels $j++; } $i++; } In this code, $j never has a value above 5, but $i goes through all values from 0 through 9.
January 1,2010 to December 31, 2010. Program Name: MonthArray.php Expected Result 2010 Calendar 1.January January 1, 2010 January 2, 2010 January 3, 2010 January 3, 2010 . . 12.December December 1, 2010 December 2, 2010 Coding Hints Create an Array to contain the Months Use for loop or foreach for program iteration. Use If/else or switch statement for conditional processing.
a specific civil status. Program Name: SalaryArray.php Expected Result STATUS WTAX % Single 20% Head of the Family 15% Married w/ 1 Child 10% Married w/ 1 Child 10% Married w/ 2 Children 9% Married w/ 3 Children 7% Married w/ 4 Children 5% Netpay Computation = (Salary -Wtax) Status: S Salary 5000 Wtax 20% NetPay 4000
+ gross salary Create an Array to contain the Civil status + wtax Use for loop or foreach for program iteration. Logic to compare civil status of array w/ grosspay against array w/ wtax for netpay computation.
a specific task, possibly acting upon a set of values given to it, or parameters, and possibly returning a single value. Function help you create organized and reusable code. They allow you to abstract out details so your code becomes more flexible and more readable. Without functions, it is impossible to write easily maintainable programs because you're constantly updating identical blocks of code in multiple places and in multiple files. Calling a Function Functions in a PHP program can be either built-in (or, by being in an extension, effectively built-in) or user-defined. Regardless of their source, all functions are evaluated in the same way: $some_value = function_name( [ parameter, ... ] );
length of a string $length = strlen("PHP"); // $length is now 3 // sin() and asin( ) are the sine and arcsine math functions $result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0 // unlink( ) deletes a file $result = unlink("functions.txt"); // false if unsuccessful With a function you pass a number of arguments in and get a value back: // add two numbers together // add two numbers together function add($a, $b) { return $a + $b; } $total = add(2, 2); // 4
length of a string $length = strlen("PHP"); // $length is now 3 // sin() and asin( ) are the sine and arcsine math functions $result = sin(asin(1)); // $result is the sine of arcsin(1), or 1.0 // unlink( ) deletes a file $result = unlink("functions.txt"); // false if unsuccessful With a function you pass a number of arguments in and get a value back: // add two numbers together // add two numbers together function add($a, $b) { return $a + $b; } $total = add(2, 2); // 4
functions, any variable you create can be used anywhere in a page. With functions, this is no longer always true. Functions keep their own sets of variables that are distinct from those of the page and of other functions. The variables defined in a function, including its parameters, are not accessible outside the function, and, by default, variables defined outside a function are not accessible inside the function. The following example illustrates this: $a = 3; function foo( ) function foo( ) { $a += 2; } foo( ); echo $a; The variable $a inside the function foo( ) is a different variable than the variable $a outside the variable; even though foo( ) uses the add-and-assign operator, the value of the outer $a remains 3 throughout the life of the page. Inside the function, $a has the value 2.
scope to be accessible from within a function, you can use the global keyword. Its syntax is: global var1, var2, ... Changing the previous example to include a global keyword, we get: $a = 3; function foo( ) { global $a; $a += 2; } foo( ); foo( ); echo $a; Instead of creating a new variable called $a with function-level scope, PHP uses the global $a within the function. Now, when the value of $a is displayed, it will be 5. You must include the global keyword in a function before any uses of the global variable or variables you want to access. Because they are declared before the body of the function, function parameters can never be global variables.
A static variable is shared between all calls to the function and is initialized during a script's execution only the first time the function is called. To declare a function variable static, use the static keyword at the variable's first use. Typically, the first use of a static variable is to assign an initial value: static var [= value][, ... ]; Example: function counter( ) { function counter( ) { static $count = 0; return $count++; } for ($i = 1; $i <= 5; $i++) { print counter( ); }
to a function? Answer Use the names from the function prototype: function commercial_sponsorship($letter, $number) { print "This episode of Sesame Street is brought to you by "; print "the letter $letter and number $number.<br>"; } commercial_sponsorship('G', 3); commercial_sponsorship($another_letter, $another_number);
to have a default value if the function's caller doesn't pass it. For example, a function to draw a table might have a parameter for border width, which defaults to 1 if no width is given? Ans. Assign the default value to the parameters inside the function prototype: function wrap_html_tag($string, $tag = 'b') function wrap_html_tag($string, $tag = 'b') { return "<$tag>$string</$tag>"; } $string = 'I am some HTML'; wrap_html_tag($string);
to a function and have it retain any changes made to its value inside the function. Ans. To instruct a function to accept an argument passed by reference instead of value, prepend an & to the parameter name in the function prototype: function wrap_html_tag(&$string, $tag = 'b') { $string = "<$tag>$string</$tag>"; } { $string = "<$tag>$string</$tag>"; } $string = 'I am some HTML'; wrap_html_tag($string); print $string;
want to define a function that takes a variable number of arguments? Ans. Pass an array and place the variable arguments inside the array: <?php // find the "average" of a group of numbers function mean($numbers) { // initialize to avoid warnings $sum = 0; // the number of elements in the array $size = count($numbers); // iterate through the array and add up the numbers for ($i = 0; $i < $size; $i++) { $sum += $numbers[$i]; }
by reference, not by value. This allows you to avoid making a duplicate copy of a variable? Ans. The syntax for returning a variable by reference is similar to passing it by reference. However, instead of placing an & before the parameter, place it before the name of the function: function &pc_array_find_value($needle, &$haystack) { foreach ($haystack as $key => $value) { foreach ($haystack as $key => $value) { if ($needle == $value) { return $haystack[$key]; } } } $html =& pc_array_find_value('The Doors', $artists);
function based on the value of a variable. For example, consider this situation, where a variable is used to determine which of three functions to call: switch($which) { case 'first': first( ); break; case 'second': case 'second': second( ); break; case 'third': third( ); break; }
accessible in three different ways from your PHP scripts, as described in this section. Collectively, this information is referred to as EGPCS (environment,GET, POST, cookies, and server).
defined in the global scope $_SERVER Variables set by the server $_ENV Environment variables $_GET Variables provided to the script via the Uniform Resource Locator (URL) $_POST Variables provided to the script via HTTP POST $_POST Variables provided to the script via HTTP POST $_COOKIE Variables provided to the script via HTTP cookies $_FILE Variables uploaded via HTTP POST file uploads $_REQUEST A combination of variables provided by GET, POST, and COOKIE methods $_SESSION Variables currently registered in the session
larger than or equal to zero, use ctype_digit( ) <?php if (! ctype_digit($_POST['age'])) { print 'Your age must be a number bigger than or equal to zero.'; } ?> ?> Validating an integer with typecasting <?php if ($_POST['rating'] != strval(intval($_POST['rating']))) { print 'Your rating must be an integer.'; } ?>
an email address a user has provided is valid. Use the is_valid_email_address( ) function . It tells you whether an email address is valid according to the rules in RFC 822. function is_valid_email_address($email){ $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'. $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'. '\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; $quoted_pair = '\\x5c[\\x00-\\x7f]'; $domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d"; $quoted_string = "\\x22($qtext|$quoted_pair)*\\x22"; $domain_ref = $atom; $sub_domain = "($domain_ref|$domain_literal)"; $word = "($atom|$quoted_string)"; $domain = "$sub_domain(\\x2e$sub_domain)*";
1 : 0; } if (is_valid_email_address('cal@example.com')) { print 'cal@example.com is a valid e-mail address'; } else { print 'cal@example.com is not a valid e-mail address'; else { print 'cal@example.com is not a valid e-mail address'; }
to generate the menu. Then validate the input by checking that the value is in the array. <?php // Generating the menu $choices = array('Eggs','Toast','Coffee'); echo "<select name='food'>\n"; foreach ($choices as $choice) { foreach ($choices as $choice) { echo "<option>$choice</option>\n"; } echo "</select>"; // Then, later, validating the menu if (! in_array($_POST['food'], $choices)) { echo "You must select a valid choice."; } ?>
to generate the menu. Then validate the input by checking that the value is in the array. <?php // Generating the menu $choices = array('Eggs','Toast','Coffee'); echo "<select name='food'>\n"; foreach ($choices as $choice) { foreach ($choices as $choice) { echo "<option>$choice</option>\n"; } echo "</select>"; // Then, later, validating the menu if (! in_array($_POST['food'], $choices)) { echo "You must select a valid choice."; } ?>
to generate the menu. Then validate the input by checking that the submitted value is in the array. <?php // Generating the radio buttons $choices = array('eggs' => 'Eggs Benedict', 'toast' => 'Buttered Toast with Jam', 'coffee' => 'Piping Hot Coffee'); foreach ($choices as $key => $choice) { echo "<input type='radio' name='food' value='$key'/> $choice<br>"; } // Then, later, validating the radio button submission if (! array_key_exists($_POST['food'], $choices)) { echo "You must select a valid choice."; } ?>
if a value is supplied, it's the correct one. If a value isn't supplied for the checkbox, then the box wasn't checked. <?php // Generating the checkbox $value = 'yes'; echo "<input type='checkbox' name='subscribe' value='yes'/> Subscribe?"; echo "<input type='checkbox' name='subscribe' value='yes'/> Subscribe?"; // Then, later, validating the checkbox if (isset($_POST['subscribe'])) { // A value was submitted and it's the right one if ($_POST['subscribe'] == $value) { $subscribed = true; } else { // A value was submitted and it's the wrong one
else { // No value was submitted $subscribed = false; } if ($subscribed) { print 'You are subscribed.'; print 'You are subscribed.'; } else { print 'You are not subscribed'; }
use an array of values to generate the checkboxes. Then, use array_intersect( ) to ensure that the set of submitted values is contained within the set of acceptable values <?php // Generating the checkboxes $choices = array('eggs' => 'Eggs Benedict', 'toast' => 'Buttered Toast with Jam', 'coffee' => 'Piping Hot Coffee'); 'coffee' => 'Piping Hot Coffee'); foreach ($choices as $key => $choice) { echo "<input type='checkbox' name='food[]' value='$key'/> $choice <br>"; } // Then, later, validating the radio button submission if (array_intersect($_POST['food'], array_keys($choices)) != $_POST['food']) { echo "You must select only valid choices."; } ?>
and year as separate elements, plug those values into checkdate( ). <?php if (! checkdate($_POST['month'], $_POST['day'], $_POST['year'])) { print "The date you entered doesn't exist!"; } ?> ?>