PHP Tags
Long tag
<?php
………………… ?>
This
is the default enabled tag of php.
Short tag
<?
………………. ?>
By
default this tag is not enabled, we need to enable it using php.ini file
|
ASP like tag
<%
………………. %>
For
PHP ASP like tags were introduced to attract the ASP developers. This also
need to enabled using php.ini file.
|
.
|
Tag.php
PHP Comments
Comments are the way you can specify, what you going to do
with the program or command. During the execution of the scripts, comments are
not going to interpret.
PHP has three Types of comments.
Single line Comment
// this is a single line comment
Multiple line
comment (C like comments)
/* this is
Multiple line
Comment*/
|
Shell script like
comment
This is also single line comment.
# Another single line comment
|
Add some comments to your previous php script and see the
out put.
What is the
different between Double
Quote and Single Quote?
Execute above scrip and
observe the difference.
Alternative Way with Single Quote
Variables
A variable is a means of storing
a value, such as text string "Hello World!" or the integer value 4. A
variable can then be reused throughout your code, instead of having to type out
the actual value over and over again. In PHP you define a variable with the
following form:
$variable_name = Value;
You assign a value to the variable using the assignment
operator (=).
If you forget that dollar, it
will not work.
NOTE: Also, variable names are case-sensitive, so use the exact
same capitalization when using a variable. The variables $a_number and $A_number
are different variables in PHP.
Note for programmers:
PHP does not require variables to be declared before being initialized.
|
PHP Variable Naming
Conventions
v There
are a few rules that you need to follow when choosing a name for your PHP
variables.
v PHP
variables must start with a letter or underscore "_".
v PHP
variables may only be comprised of alpha-numeric characters and underscores.
a-z, A-Z, 0-9, or _ .
v Variables
with more than one word should be separated with underscores. $my_variable
v Variables
with more than one word can also be distinguished with capitalization.
$myVariable
Predefine variables
PHP provides a large number of
predefined variables to all scripts. The variables represent everything from
external variables to built-in environment variables, last error messages to
last retrieved headers.
- Superregionals — Superglobals are built-in variables that are always available in all scopes
- $GLOBALS — References all variables available in global scope
- $_SERVER — Server and execution environment information
- $_GET — HTTP GET variables
- $_POST — HTTP POST variables
- $_FILES — HTTP File Upload variables
- $_REQUEST — HTTP Request variables
- $_SESSION — Session variables
- $_ENV — Environment variables
- $_COOKIE — HTTP Cookies
- $php_errormsg — The previous error message
- $HTTP_RAW_POST_DATA — Raw POST data
- $http_response_header — HTTP response headers
- $argc — The number of arguments passed to script
- $argv — Array of arguments passed to scrjtmnipt
Constants
A
constant is an identifier (name) for a simple value. As the name suggests, that
value cannot change during the execution of the. A constant is case-sensitive
by default. By convention, constant identifiers are always uppercase.
|
Printing Variable
Values
If
you want to print a value of a variable you can directly print it using “echo”.
|
Use of Double Quote
and Single Quote
There are two different ways of printing text using PHP
script. Using double or single quoted.
|
<?php
$variable
= 'Saman';
echo
'My name is $variable';
?>
|
<?php
$variable
= 'Saman';
echo
"My name is $variable";
?>
|
Double_quote.php | Single_quote.php |
If a variable is to be printed out amongst the words of a
string then the whole thing must be contained within double quotes. If we wish to interpolate a variable into a sentence
this is how we do it. Why, though? What if we used single quotes?
|
v “.”
is the string concatenation operator in PHP.
Data Types of PHP
·
Booleans
This
is the simplest type. A Boolean expresses a truth value. It can be either TRUE or FALSE.
·
Integers
An integer is a number of the set Z = {..., -2,
-1, 0, 1, 2, ...}.
The size of an
integer is platform-dependent, although a maximum value of about two billion is
the usual value (that's 32 bits signed). PHP does not support unsigned integers.
Integer size can be determined using the constant PHP_INT_SIZE, and maximum
value using the constant PHP_INT_MAX
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
·
Floating point numbers
Floating point numbers (also known
as "floats", "doubles", or "real numbers") can be
specified using any of the following syntaxes:
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
$b = 1.2e3;
$c = 7E-10;
·
Strings
A string is series of characters.
Before PHP 6, a character is the same as a byte. That is, there are exactly 256
different characters possible.
·
Arrays
An array in PHP
is actually an ordered map. A map is a type that associates values to keys.
This type is optimized for several different uses; it can be treated as an
array, list (vector), hash table (an implementation of a map), dictionary,
collection, stack, queue, and probably more. As array values can be other
arrays, trees and multidimensional arrays are also possible.
$arr = array("foo" => "bar", 12 => true);
·
Objects
Instance
of a Class is call as an object. Using new key word we create object
·
Resources
A resource is a special variable,
holding a reference to an external resource. Resources are created and used by
special functions.
·
NULL
The special NULL value represents a
variable with no value. NULL is the only possible value of type NULL.
A variable is considered to be null
if:
·
it has been assigned the constant NULL.
·
it has not been set to any value yet.
·
it has been unset().
Four
scalar types:
- boolean integer float string
Two compound types:
- array object
The type of a
variable is usually not set by the programmer; rather, it is decided at runtime
by PHP depending on the context in which that variable is used.
To get the
data type of some particular variable, we can use gettype() function.
|
Arithmetic Operators
Arithmetic Operators
|
||
Example
|
Name
|
Result
|
-$a
|
Negation
|
Opposite of $a.
|
$a + $b
|
Addition
|
Sum of $a and $b.
|
$a - $b
|
Subtraction
|
Difference of $a and $b.
|
$a * $b
|
Multiplication
|
Product of $a and $b.
|
$a / $b
|
Division
|
Quotient of $a and $b.
|
$a % $b
|
Modulus
|
Remainder of $a divided by $b.
|
$a++
|
Increment
|
$a+1
|
$a--
|
Decrement
|
$a-1
|
Example on Arithmetic Expressions
|
Assignment Operators
The basic assignment operator is
"=". Your first inclination might be to think of this as "equal
to". Don't. It really means that the left operand gets set to the value of
the expression on the rights (that is, "gets set to").
|
Note: The assignment copies the original variable to the new one
(assignment by value), so changes to one will not affect the other.
Comparison Operators
Comparison
Operators
|
||
Example
|
Name
|
Result
|
$a == $b
|
Equal
|
TRUE if $a is equal to $b.
|
$a === $b
|
Identical
|
TRUE if $a is equal to $b, and they are of the same type.
(introduced in PHP 4)
|
$a != $b
|
Not equal
|
TRUE if $a is not equal to $b.
|
$a <> $b
|
Not equal
|
TRUE if $a is not equal to $b.
|
$a !== $b
|
Not identical
|
TRUE if $a is not equal to $b, or they are not of the same
type. (introduced in PHP 4)
|
$a < $b
|
Less than
|
TRUE if $a is strictly less than $b.
|
$a > $b
|
Greater than
|
TRUE if $a is strictly greater than $b.
|
$a <= $b
|
Less than or equal to
|
TRUE if $a is less than or equal to $b.
|
$a >= $b
|
Greater than or equal to
|
TRUE if $a is greater than or equal to $b.
|
Logical Operators
Logical Operators
|
||
Example
|
Name
|
Result
|
$a and $b
|
And
|
TRUE if both $a and $b are TRUE.
|
$a or $b
|
Or
|
TRUE if either $a or $b is TRUE.
|
$a xor $b
|
Xor
|
TRUE if either $a or $b is TRUE, but not both.
|
! $a
|
Not
|
TRUE if $a is not TRUE.
|
$a && $b
|
And
|
TRUE if both $a and $b are TRUE.
|
$a || $b
|
Or
|
TRUE if either $a or $b is TRUE.
|
Flow Control
If….else Condition
Syntax: if (condition
here) { }
if (condition
here) { }
else { }
else { }
Example
|
If …elseif…else Condition
Syntax: if
(condition here) { }
elseif ( another condition here ) { }
elseif ( another condition here ) { }
elseif
( yet another condition here ) { }
else { }
//none of the other conditions
Example
|
Question:
Write a program to if marks value
is given calculate the Grade of the subject.
Marks >80: Grade A
Marks between 70 and 80: Grade B
Marks between 60 and 70: Grade C
Else: Fail
While loop
Syntax: WHILE
(condition here) {}
Example
|
do-while loop
Syntax: do {
} while (Condition here);
?>
?>
Example
|
For loop
Syntax: for (first condition, test
condition, increment condition ) { }
Example
|
Foreach loop
This
simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when
you try to use it on a variable with a different data type or an uninitialized
variable.
Syntax: foreach( array_expression as $value){ }
foreach( array_expression as
$key => $value){ }
We will discuss
this under arrays.
Continue and break
- Break ends execution of the current for, foreach, while, do-while or switch structure.
- Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
|
Switch ….Case
The switch statement is similar
to a series of IF statements on the same expression. In many occasions, you may
want to compare the same variable (or expression) with many different values,
and execute a different piece of code depending on which value it equals to.
This is exactly what the switch statement is for.
|
String Manipulation
Strings
A string
is series of characters. Before PHP 6, a character is the same as a byte. That
is, there are exactly 256 different characters possible. This also implies that
PHP has no native support of Unicode.
A string
literal can be specified in four different ways:
·
single quoted
·
double quoted
·
heredoc syntax
·
nowdoc syntax
Quoted Strings
The easiest way to specify a simple string is to enclose it
in single quotes (the character '). Enclosing the string in double-quotes
("), will allow PHP to understand additional escape sequences for special
characters:
Example:
|
Escape Characters
Escaped characters
|
|
Sequence
|
Meaning
|
\n
|
Line feed (LF or 0x0A (10) in
ASCII)
|
\r
|
carriage return (CR or 0x0D (13)
in ASCII)
|
\t
|
horizontal tab (HT or 0x09 (9)
in ASCII)
|
\v
|
vertical tab (VT or 0x0B (11) in
ASCII) (since PHP 5.2.5)
|
\f
|
form feed (FF or 0x0C (12) in
ASCII) (since PHP 5.2.5)
|
\\
|
backslash
|
\$
|
dollar sign
|
\"
|
double-quote
|
\[0-7]{1,3}
|
the sequence of characters
matching the regular expression is a character in octal notation
|
\x[0-9A-Fa-f]{1,2}
|
the sequence of characters
matching the regular expression is a character in hexadecimal notation
|
Example
|
Concatenating Strings
Using the concatenate operator (.), strings can be easily joined together.
Using the concatenate operator (.), strings can be easily joined together.
<?php
$str_1 = 'This'; $str_2 = 'is a'; $str_3 = 'string.'; $str = $str_1. " " .$str_2. " " .$str_3; echo $str; ?> |
Heredoc syntax
In order to allow people to
easily write large amounts of text from within PHP, but without the need to
constantly escape things, heredoc syntax was developed. Heredoc might be a
little tricky to understand at first, but it is actually a big help. Put
simply, it allows you to define your own string limiter so that you can make it
something other than a double or single quote.
Example
|
There are several key things to note about heredoc, and the
example above:
- You can use anything you like; "EOT" is just an example
- You need to use <<< before the delimiter to tell PHP you want to enter heredoc mode
- Variable substitution is used in PHP, which means you do need to escape dollar symbols – if you do not, PHP will attempt variable replacement.
- You can use your delimiter anywhere in the text, but not in the first column of a new line
- At the end of the string, just type the delimiter with no spaces around it, followed by a semi-colon to end the statement
Nowdoc syntax
Introduced
with PHP 5.3.0 students need to find about this.
String Manipulation functions
trim() : Removes leading and tailoring
spaces
strtolower():Returns string with all
alphabetic characters converted to uppercase
strtoupper():Returns string with all
alphabetic characters converted to lowercase
substr() : Returns the portion of
string specified by the start and length parameters
strcmp(): Compare two strings, this is a
case sensitive comparison
strlen(): Return the length of a string
Examples on String manipulation function
|
Exercises & Practices
1 What is “var_dump” ? Give an
eexample on “var_dump”.
2 Write a program to print 1
to 100.
3
“-----071-3234443-----“this is a string got out from a communication line. This
string should contain a telephone number. But it contains leading and tailoring
dashes. Write a program to retrieve the telephone number. *Hint use string
manipulation functions.
No comments:
Post a Comment