Unit-3 PHP
Unit-3 PHP
2CEIT6PE1
WEB TECHNOLOGY
UNIT 3
PHP: Flow control, building blocks, Functions, Array, Objects and
Strings
Variables are used for storing values, like text strings, numbers or
arrays.
When a variable is declared, it can be used over and over again in
your script.
All variables in PHP start with a $ sign symbol.
The correct way of declaring a variable in PHP:
PHP Variables
In PHP, a variable does not need to be declared before adding a value to it.
In the example above, you see that you do not have to tell PHP that the
variable is of which datatype.
PHP automatically converts the variable to the correct data type,
depending on its value.
PHP Variables
If we look at the code you see that we used the concatenation
operator two times. This is because we had to insert a third string (a
space character), to separate the two strings.
PHP Data Types
The PHP var_dump() function returns the data type and value.
<!DOCTYPE html>
<html>
<body>
<?php
$a = 32;
echo var_dump($a) . "<br>";
$b = "Hello world!";
echo var_dump($b) . "<br>";
PHP Data Types
$c = 32.5;
echo var_dump($c) . "<br>";
The output of above program:
$d = array("red", "green", "blue");
int(32)
echo var_dump($d) . "<br>"; string(12) "Hello world!"
float(32.5)
// Dump two variables
echo var_dump($a, $b) . "<br>"; array(3) { [0]=> string(3) "red"
?>
[1]=> string(5) "green" [2]=>
string(4) "blue" }
</body>
</html> int(32) string(12) "Hello world!"
PHP Operators
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
PHP Operators
PHP Operators
PHP Operators
PHP Operators
Increment / Decrement Operators
Operator Name Description
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
PHP Conditional Statements
If more than
one line should
be executed if a
condition is
true/false, the
lines should be
enclosed within
curly braces { }
PHP Conditional Statements
The following
example will output
"Have a nice
weekend!" if the
current day is Friday,
and "Have a nice
Sunday!" if the
current day is
Sunday. Otherwise it
will output "Have a
nice day!":
PHP Conditional Statements
The value of the expression is then compared with the values for
each case in the structure. If there is a match, the block of code
associated with that case is executed.
Use break to prevent the code from running into the next case
automatically. The default statement is used if no match is found.
PHP Conditional Statements
PHP Loops
Often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal
lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:
while - loops through a block of code while a specified condition is
true
do...while - loops through a block of code once, and then repeats the
loop as long as a specified condition is true
for - loops through a block of code a specified number of times
PHP Loops - While
The do...while statement will always execute the block of code once, it
will then check the condition, and repeat the loop while the condition
is true.
The next example defines a loop that starts with i=1. It will then
increment i with 1, and write some output. Then the condition is
checked, and the loop will continue to run as long as i is less than, or
equal to 5:
PHP Loops – Do ... While
PHP Loops - For
PHP Loops - For
Parameters:
init: Mostly used to set a counter (but can be any code to be executed
once at the beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code
to be executed at the end of the loop)
PHP Loops - For
The example below defines a loop that starts with i=1. The loop will
continue to run as long as i is less than, or equal to 5. i will increase
by 1 each time the loop runs:
PHP Loops - Foreach
The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array.
For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
PHP Loops - Foreach
The following example demonstrates a loop that will print the values
of the given array:
PHP Functions
PHP has over 1000 built-in functions that can be called directly,
from within a script, to perform a specific task.
Syntax
Give the function a name that reflects what the function does.
The function name can start with a letter or underscore (not a
number).
User Defined Function in PHP
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() { Output:
echo "Hello world!";
} Hello world!
writeMsg();
?>
</body>
</html>
PHP Function Arguments
The scope of a variable is the part of the script where the variable
can be referenced/used.
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
<?php </body>
$x = 5; </html>
$y = 10;
function myTest() {
global $x, $y; Output: 15
$y = $x + $y;
}
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a
further job.
To do this, use the static keyword when you first declare the variable:
If you have a list of items (a list of car names, for example), storing the
cars in single variables could look like this:
PHP Arrays
However, what if you want to loop through the cars and find a specific
one? And what if you had not 3 cars, but 300?
An array can hold all your variable values under a single name. And you
can access the values by referring to the array name.
Each element in the array has its own index so that it can be easily
accessed.
PHP Arrays
When storing data about specific named values, a numerical array is not
always the best way to do it.
With associative arrays we can use the values as keys and assign values
to them.
PHP Associative Arrays
This example is the same as the one above, but shows a different way of
creating the array:
PHP Associative Arrays
PHP Multidimensional Arrays
OUTPUT
I like Volvo, BMW and Toyota.
String & in-built functions
Single quote
Double quote
heredoc syntax: <<<
Syntax
$nameOfVariable = <<< identifier
// string
// string
// string
identifier;
DOs and DON’Ts of heredoc syntax usage
The variable should start with <<< and identifier in the first line. After
the last line, there must be the same identifier again.
Use curly brackets {} to contain any other variable that you want to
display the contents of as part of the strings.
User defined function
Syntax:
function functionname()
{
//code to be executed
}
Types of functions:
Example: Assume we have an HTML page that contains a hyperlink with parameters:
index.html Test.php
<html>
<html> <body>
<body> <?php
echo "Study " .
<a href="test.php?subject=WT&technology=PHP">Test $GET</a> $_GET['subject'] . " at " .
</body> $_GET[‘technology'];
?>
</html> </body>
</html>
PHP Global Variables - Superglobals
PHP $_POST
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with
method="post".
$_POST is also widely used to pass variables.
Example:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name; } }
?>
PHP Global Variables - Superglobals
PHP $_REQUEST
PHP $_REQUEST is a PHP super global variable which is used to
collect data after submitting an HTML form.
The $_REQUEST function is used to get the form information sent
with POST method or GET method.
PHP Global Variables - Superglobals
PHP $_ENV:
$_ENV is another superglobal associative array in PHP.
It stores environment variables available to current script now been
deprecated.
Environment variables are imported into global namespace. Most of these
variables are provided by the shell under which PHP parser is running.
Hence, list of environment variables may be different on different platforms.
This array also includes CGI variables in case whether PHP is running as a
server module or CGI processor.
PHP library has getenv()function to retrieve list of all environment variables
or value of a specific environment variable
PHP Global Variables - Superglobals
PHP $_ENV:
Getenv() function: To retrieve list of all environment variables or value of a
specific environment variable
Example:
<?php
$arr=getenv();
foreach ($arr as $key=>$val)
echo "$key=>$val";
?>
PHP String Operators
Example
<?php
$list=`dir *.php`;
echo "$list";
?>
Error Control Operators
In PHP @ symbol is defined as Error Control Operator. When it is prefixed to
any expression, any error encountered by PHP parser while executing it will be
suppressed and the expression will be ignored.
Following code tries to open a non-existing file for read operation, but PHP
parser reports warning
Example
<?php
$fp=fopen("nosuchfile.txt","r");
echo "Hello World
"; ?>