Week 3 PHP Scripting-Part 1: Basic Syntax
Week 3 PHP Scripting-Part 1: Basic Syntax
A PHP scripting block always starts with <?php and ends with ?>. On servers with shorthand support we are allowed to start a scripting block with <? and end with ?>. Other style that can be used is by including PHP script in the <script language = PHP>.....</script> block.
For maximum compatibility, it is recommended that we use the standard form: <?php .. ?> The file must have a .php extension. Otherwise, the PHP code will not be executed.
Basic Syntax
When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
Basic Syntax
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. A PHP scripting block can be placed anywhere in the document. <html> <head> <?php . ?> <title>Basic PHP </title> </head> <?php ?> </html>
4
Most of the time you will see PHP embedded in HTML documents, as in this example.
Basic Syntax
The following page is to verify the availability of PHP on your server with a lot of information about the PHP itself and the server it's running on:
Comments
Comments are explanatory remarks which are not executed by the server. PHP supports three types of comments # this is a comment // this is also a comment /* this is a larger comment that spans more than one line ...*/ Example <?php // This is a comment /* This is a comment block 6 */ ?>
Variables
Variable is used for storing a value like string, a number or an array.
Variables
Example <?php $txt = Welcome to PHP World!"; $x = 5; ?>
$var_name = value;
The rules of giving the name to a variable :
9 After the dollar sign symbol ($), a variable name must start with a letter or an underscore "_" 9 A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) 9 A variable name should not contain spaces. If a variable name uses more than one word, it should be separated with an underscore ($my_var), or with capitalization ($myVar)
7
Valid and invalid PHP variables: $myvar = "foo"; // Assigns the string 'foo' badvar = "test"; // Invalid, no $ symbol $another(test)var = "bad"; // Invalid, can't use () $php5 = "is cool"; // Correct Syntax $5php = "is wrong"; // Invalid, starts with number
8
Variables
PHP is a loosely typed language, a variable does not need to be declared before a value is assigned to it. In PHP, the variable is declared automatically when you use it. Also, the data type of a variable does not have to be specified. PHP automatically converts the variable to the correct data type, depending on its value. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it.
9
Data Types
PHP basic data types are as follows: integer - whole numbers double - real numbers string - strings of characters (values are enclosed in quotes) Boolean true or false Others include array (a set or group of variables of the same type) and object (class instances )
10
Data Types
Integers
integer values use three mathematical bases: decimal (base 10), octal (base 8), and hexadecimal (base 16 ) examples:
Data Types
Doubles
real numbers or numbers that have decimal point if the number is too big or too small, it can be represented using exponential notation of the following form: 7.31e-4 (7.31 x 10-4) to represent 0.000731 1.625e5 (1.625 x105) to represent 162550
where e stands for exponent (x10). The number before it is called mantissa, and the number after it is the power of 10. examples:
$x = 0.00051; /* Standard Floating Point Notation */ $y = .051e-2; /* Exponential Notation of the same number */
/* Standard Decimal Notation */ /* Same number, Octal Notation (starts with the letter O)*/ /* Hexadecimal Notation */
11
12
Type Casting
Type casting in PHP means to treat a variable of one type as if it was another (without actually changing its type.) Implemented in the following form: (data_type)$variable For example: $quantity = 0; $amount = (double)$quantity;
$quantity is initially set up as an integer with a value of zero. The next line treats $quantity as a double type and assigns its value to $amount. $amount is now a double with a value of zero and $quantity is still an integer with a value of zero.
13
Type Casting
Type casts can also be automatic, such as adding a double to an integer, the result will be a double even if it is stored in the original integer variable. For example: $int = 12; $double = 10.37; $int = $int + $double; echo $int; which will display: 22.37
14
Output Operations
There are two basic statements to output text with PHP: echo and print. Both are used to output one or more strings. The echo() is slightly faster than print(). The print() returns true/false, but echo() does not. The parentheses are optional, they cannot be used for more than one string. Syntax: echo | print string; echo | print string1, string2, , stringn; echo | print (string);
- string must be enclosed in quotes (single or double) - more than one string must be separated by commas
15
Output Operations
HTML tags can also be included in the strings in order to format the printed text. Examples:
1)
<?php echo Hello, there World!; ?> Output: Hello, there World!
2) Using HTML tags: <?php echo "This text<br>spans multiple<br>lines."; ?> Output: This text spans multiple lines.
16
Output Operations
3) To print more than one parameter of strings:
Output Operations
5) To show the difference of single and double quotes. Single quotes will print the variable name, not the value: <?php $color = "red"; echo "Roses are $color"; echo "<br >"; echo 'Roses are $color'; ?> Output: Roses are red Roses are $color
17 18
Output Operations
There is also the shortcut syntax of echo, which is as follows:
Output Operations
Using Quotes in the echo and print.
Be careful when using HTML code or any other string that includes quotes! echo and print use quotes to define the beginning and end of the string. Therefore, if the string contains quotations:
Don't use quotes inside the string Escape the quotes that are within the string with a backslash - place a backslash directly before the quotation mark ( \) Use single quotes (apostrophes) for quotes inside the string.
19 20
<html> <body> <?php $color = "red"; ?> <p>Roses are <?=$color?></p> </body> </html>
Output Operations
Using Quotes in the echo and print. (Cont.)
Example: <?php // This won't work because of the quotes around specialH5! echo "<h5 class = "specialH5"> I love using PHP!</h5>"; // OK because we escaped the quotes! echo "<h5 class = \"specialH5\">I love using PHP!</h5>"; // OK because we used an apostrophe (single quote) echo "<h5 class = 'specialH5'>I love using PHP!</h5>"; ?> To output a string that includes quotations, either use an apostrophe ( ' ) or escape the quotations by placing a backslash in front of it ( \"). The backslash will tell PHP that the quotation is to be used within the string and NOT to be used to delimit (mark) the string.
21
Output Operations
Formatting Output
To format the output PHP provides two functions printf() and sprintf() (to be used with echo and print). The printf() function is used to format the displayed data. Syntax: printf(output_format, param1, param2, )
- where, the param1, param2, , is the output value to be formatted, can be in form of expression or variable. - each of output_format is a format code for the param1, param2, in the form of a percentage symbol (%), followed by a field width, and a type specifier. - the field width is an integer literal (for integers formatting) or two integer literals separated by a decimal point (for floats/doubles formatting) - the most common type specifiers are: s for string, d for integers, and f for floats & doubles, e for exponential notation of doubles.
22
Output Operations
Formatting Output (Cont.)
Examples of output_format: %12s a string field of 12 characters %5d an integer field of 5 digits %3.2f a float/double field of 6 spaces, with two digits to the right of the decimal point, the decimal point, and three digits to the left.
Output Operations
Formatting Output (Cont.)
23
printf() allows padding out an argument value to a fixed width. Any character can be used for the padding, either to the left or the right of the value. Padding is useful for adding leading zeroes to numbers, and for rightaligning strings. To add padding, insert a padding specifier between the '%' character and the type specifier. A padding specifier takes the format: <padding character><width> <padding character> can be a zero or a space. If not specified, spaces are used. To use a different character, write an apostrophe (') followed by the character to use. <width> is the number of characters to pad the value out to. A positive number adds padding to the left; a negative number adds 24 padding to the right.
Output Operations
Formatting Output (Cont.)
Examples:
Output Operations
Formatting Output (Cont.)
The sprintf() function is identical to printf(), except that rather than directly outputting the result, it returns the value so that you can store it in a variable (or otherwise manipulate it). This is useful if you want to process the result before displaying it, or store it in a database. sprintf() uses the same syntax as printf(). Example:
Output:
25
26
Output Operations
Formatting Output (Cont.)
The number_format() function formats a number with grouped thousands with comma (,) as the thousands separator. Syntax number_format(number,[decimals,decimalpoint,separator])
- number is required, is the value to be formatted. If no other parameters are set, the number will be formatted without decimals - decimals is optional, to specify how many decimals with a dot (.) as decimal point. - decimalpoint is optional, to specify what string to use for decimal point. - separator is optional, to specify the character to use for thousands separator. If this parameter is given, all other parameters are required as well.
Output Operations
Formatting Output (Cont.)
Example:
Note: This function supports one, two, or four parameters (not three).
27 28
String Manipulations
Concatenation
Concatenation is joining two ore more strings, which can be performed using the dot notation. Example: <?php $txt1 = "Hello there, World!"; $txt2 = Have a nice day!"; $greet = $txt1 . " " . $txt2 echo $greet; ?>
29
String Manipulations
Using the strlen() function
The strlen() function is used to return the length (number of characters) of a string.
It is used in the form: strlen(string)
Example:
<?php echo strlen("Hello world!"); ?>
12 The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).
30
String Manipulations
Using the strpos() function
The strpos() function is used to search for the position of the first character of a substring in a long string.
It is used in the form: strpos(string, substring )
If a match is found, it will return the position of the first matched character. Otherwise, it will return a false. To find the position of string "world" in a string:
<?php echo strpos("Hello world!","world"); ?>
* Multiplication
/ Division % Modulus
The output will be: 6 The position of the string "world" in the string is position 6, because the first position in the string is always 0, and not 1.
31
For example, $a = 5; assigns the value 5 to $a. This assignment can be combined with some other operators like: $a += 2;
- if $a already had a value of 5, then after this statement it would be 7, which is equivalent to:
$a = $a + 2;
$a += 1; or
$a -= 1;
PHP provides the increment and decrement operators, respectively. They are listed as follows:
++value Pre-Increment --value Pre-Decrement Adds 1 to the value before processing the expression which uses the value Subtracts 1 from the value before processing the expression which uses the value Adds 1 to the value after processing the expression which uses the value Subtracts 1 from the value after processing the expression which uses the value
35
Checks for equal values Checks for equal values and data types Checks for values not equal Checks for values not equal or not the same Not Identical data type Checks for one value being less than the Less than second Checks for one value being greater than the Greater than second Less than or Equal Checks for on value being less than or equal to to the second Greater than or Checks for on value being greater than or Equal to equal to the second
37
Xor Checks if only one of two statements is true ! Checks if a statement is not true
38
will give a result of 4 will give a result of 2 will give a result of 11 will also give 11 will give a result of 15 will give a result of 10 will give a result of 13 will give a result of 14
if - to execute some code only if a specified condition is true if...else - to execute some code if a condition is true and another code if the condition is false if...elseif....else - to select one of several blocks of code to be executed
2) The switch Statement - to select one of many blocks of code to be executed
42
Parentheses are essential to create a complex expression so that it is easier to see the process of evaluation. 41
The if Statements
Syntax of the if statement:
The if Statements
The syntax of the ifelseif else statement:
if (condition) { statement; } elseif (condition) { statement; } elseif (condition) { statement; } else { statement; }
if (condition) { statement; }
Syntax of the ifelse statement: if (condition) { statement; } else { statement; }
43
Each of the condition is a Boolean/logical expression and statement is any PHP executable statement
44
The if Statements
Examples: 1)
if ($x < 0) { echo $x is negative.; } 2)
The if Statements
More example: $temp = 25; if ($temp > $idealtemp) { print "Add cold water; } elseif ($temp < $idealtemp) { print "Add hot water; } else { print "Add more water; }
45 46
$finished = true; $pgs_completed = 50; if ( ($pgs_completed >= 50) || $finished)) { echo "Hey you're done, get some sleep!<br>"; } else { echo "You're not done yet - no sleep tonight!<br>"; }
switch (n) { case label1: statement(s); break; case label2: statement(s); break; case labeln: statement(s); break; default: statement(s); }
9The single expression n (most often a variable), is evaluated. 9The value of the expression is then compared with the values for each case in the structure. 9If there is a match, the statement(s) associated with that case is executed until it encounters the break statement. 9The break is used to prevent the code from running into the next case automatically. 9The default statement is used if no match is found
47
Example: $n = 1; while($n <= 5) { echo "The number is " . $n . "<br />"; $n++; }
50
Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).
53 54
User-defined Functions
User-defined function is a function that is created by the programmer. It contains a block of PHP code that can be executed once or many times. To keep the browser from executing a script when the page loads, put the script into a user-defined function. A function will be executed by a call to the function. A function can be called from anywhere within a page. The function must first be defined before use, by using the function keyword followed by a given name, followed by parentheses with optional parameter(s) in it. Code for the function is placed in between the braces after the function header, as follows: function function_name ([parameter_list]) { statement(s); }
55 56
2)
for ($count = 1; $count <= 10; $count++) { if ( ($count % 3) == 0) { echo "$count is divisible by 3!<BR>"; } }
User-defined Functions
A parameter_list is one or more data placed within the parentheses at the function header. Some functions do not have parameters, therefore empty parentheses are placed after the identifier. The function_name given following the rules of giving a variable name except that it does not start with the dollar sign. The name is case insensitive. The function name is given to reflect what the function does. To call a function is simply by using the function name followed by parentheses, as follows: function_name();
User-defined Functions
Example a function that displays a message:
Function definition
Output:
Function call
57
58
User-defined Functions
A Function with Parameters
Parameters are used to add more functionality to a function. A parameter is like a variable. Parameters are specified after the function name, inside the parentheses. When the function is called, the argument must be added inside the parentheses at the function call. This is to pass the value from the argument to the function parameter. They are used in the following form:
function_name (param1, param2, ) { ... }
User-defined Functions
The number of parameters at the function header must agree with the number of arguments at the function call. Example:
Output:
..
function_name(arg1, arg2, );
59 60
User-defined Functions
A Function that Returns a Value To let a function return a value, the function must have the return statement. The function call must be assigned to a variable or displayed directly in an input operation. Example:
User-defined Functions
Pass by Value and Pass by Reference
Pass by value means that the function call will pass the values from the arguments to the function parameters. Example:
Output:
Output:
61 62
User-defined Functions
Pass by Value and Pass by Reference (Cont.)
Pass by reference means that the function call will pass the address along with the values of the arguments to the function parameters. For the parameters to receive the address of the arguments the ampersand symbol (&) is placed before the parameter name. Example:
User-defined Functions
Setting Default Values for Function Parameters
A parameter can be set to have a default value if the function call doesn't pass any argument. For example, the following function prints NULL in case there is no value passed to the parameter of this function.
<?php function printMe($param = NULL) { print $param; } printMe("This is test"); printMe(); ?>
Output:
63
Variable Scope
Every variable has the scope in which part of script it resides. a variable is accessible anywhere within a script once it had been defined.
Variable Scope
Example using global variable:
Variable defined within a function has its own scope variables defined within a function are not available outside of it variables defined outside of a function are not available within the function. To alter variable scope within a function, use the global statement, for example: function function_name() { global $var; } $var = value;
65
Output:
66
Static Variable
Static variables do not get destroyed when the function terminates. To create a static variable within a function, use the static statement, as follows: static $var = value; Example:
Output:
67