PHP I Slides
PHP I Slides
4
1
3 PHP
module
Apache
2
https://www.apachefriends.org/download.html
<?php
…
?>
PHP Hello World
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
Output:
Variable x inside function is:
Variable x outside function is: 5
LOCAL SCOPE
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
<?php
function myTest() {
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
Output:
Variable x inside function is: 5
Notice: Undefined variable: x in C:\xampp\
htdocs\square.php on line 12
Variable x outside function is:
global keyword
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
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Output:
15
Global Array
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable. This array is also accessible from within functions and can be
used to update global variables directly.
<?php
$x = 5;
$y=15;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo "<p>Variable x outside function is: $y</p>";
?>
myTest();
echo $y; // outputs 20
?>
Output:
20
Static Scope
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
<?php
Function mytest()
{
Static $x=0;
echo $x;
$x++;
}
mytest();
mytest();
mytest();
?>
Output:
0
1
2
Echo
The PHP command ‘echo’ is used to output the
parameters passed to it
The typical usage for this is to send data to the
client’s web-browser
Syntax
void echo (string arg1 [, string argn...])
In practice, arguments are not passed in
parentheses since echo is a language construct
rather than an actual function
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as “\n”
or “\\”)
PHP Echo
PHP echo is a language construct not a function, so you don't
need to use parenthesis with it. But if you want to use more than
one parameters, it is required to use parenthesis.
The syntax of PHP echo is given below:
void echo ( string $arg1 [, string $... ] )
PHP echo statement can be used to print string, multi line
strings, escaping characters, variable, array etc.
PHP echo: printing string
PHP echo and print Statements
echo and print are more or less the same. They
are both used to output data to the screen.
The differences are small: echo has no return
value while print has a return value of 1 so it
can be used in expressions. echo can take
multiple parameters (although such usage is
rare) while print can take one argument. echo is
marginally faster than print.
PHP Variable
PHP Variable: Sum of two variables
PHP Variable: case sensitive
PHP Variable: Rules
PHP variables must start with letter or underscore only.
PHP variable can't be start with numbers and special symbols.
File: variablevalid.php
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>
Output:
hello hello
PHP Data Types
Variables can store data of different types
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string is a sequence of characters, like "Hello
world!".
A string can be any text inside quotes. You can
use single or double quotes:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>"; echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
A Boolean represents two possible states:
TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing.
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP
var_dump() function returns the data type and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW"
[2]=> string(6) "Toyota" }
PHP Object
An object is a data type which stores data and information on
how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the
class keyword. A class is a structure that can contain properties
and methods:
<?php
class Car {
function Car() {
$this->model = "VW";
}}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model; ?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to
it.
Note: If a variable is created without a value, it is automatically assigned
a value of NULL.
Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output
NULL
PHP Resource
The special resource type is not an actual data type. It is the
storing of a reference to functions and resources external to
PHP(such as database connections).
A common example of using the resource data type is a
database call.
The following code shows how to get the database resource
identifier by requesting the MySQL connection. In this code, the
database information is specified for the mysqli_connect() and it
returns MySQL connection object as a resource identifier.
$conn = mysqli_connect(localhost,"root","admin","animals");
While working with files, we need to get the file resource
identifier. with the reference to this identifier, we can perform
the write, append and more file manipulation operations. The
following PHP code is used to create a file resource object
reference.
$fp = fopen("index.php",'r');
PHP String
They are sequences of characters, like "PHP supports string
operations".
Following are valid examples of string
$string_1 = "This is a string in double quotes“;
$string_2 = "This is a somewhat longer, singly quoted string“;
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas
doubly quoted strings replace variables with their values as well
as specially interpreting certain character sequences.
PHP String
<?php $variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n"; print($literally);
?>
This will produce the following result −
My $variable will not print!\n
My name will print
String Concatenation Operator
To concatenate two string variables together,
use the dot (.) operator −
<?php $string1="Hello World";
$string2="1234"; echo $string1 . " " .
$string2;
?>
This will produce the following result −
Hello World 1234
strlen() function
The strlen() function is used to find the length of a string.
find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
This will produce the following result −
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)
strpos() function
The strpos() function is used to search for a string or character
within a string.
If a match is found in the string, this function will return the
position of the first match. If no match is found, it will return
FALSE.
Let's see if we can find the string "world" in our string −
<?php echo strpos("Hello world!","world");?>
This will produce the following result −
6
As you see the position of the string "world" in our string is
position 6. The reason that it is 6, and not 7, is that the first
position in the string is 0, and not 1.
Strings (I)
•
A string is a sequence of chars
$stringTest = “this is a sequence of chars”;
echo $stringTest[0]; output: t
echo $stringTest; output: this is a sequence of chars
•
A single quoted strings is displayed “as-is”
$age = 37;
$stringTest = 'I am $age years old'; // output: I am $age years old
$stringTest = “I am $age years old”; // output: I am 37 years old
•
Concatenation
$conc = ”is “.”a “.”composed “.”string”;
echo $conc; // output: is a composed string
$newConc = 'Also $conc '.$conc;
echo $newConc; // output: Also $conc is a composed string
PHP Concatenation
> The concatenation operator (.) is used to put
two string values together.
> To concatenate two string variables together,
use the concatenation operator:
PHP Concatenation
Hello PHP
PHP Operators
> Arithmetic
> Assignment
> Comparison
> Logical
PHP Operators
PHP Operators
PHP Operators
Comparison Operator
===
Identical
$x === $y Returns true if $x is equal to $y, and
they are of the same type
!==
Not identical
$x !== $y Returns true if $x is not equal to $y,
or they are not of the same type
PHP Operators
PHP Increment / Decrement
Operators
The PHP increment operators are used to
increment a variable's value.
The PHP decrement operators are used to
decrement a variable's value.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Array Operators
The PHP array operators are used to compare
arrays.
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same
key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
var_dump($x === $y);
?>
</body>
</html>
Output:
bool(false)
Bitwise Operators
& (Bitwise AND) : This is a binary operator i.e.
it works on two operand. Bitwise AND operator
in PHP takes two numbers as operands and
does AND on every bit of two numbers. The
result of AND is 1 only if both bits are 1.
| (Bitwise OR) : This is also binary operator i.e.
works on two operand. Bitwise OR operator
takes two numbers as operands and does OR
on every bit of two numbers. The result of OR is
1 any of the two bits is 1.
Bitwise Operators
^ (Bitwise XOR ) : This is also binary operator
i.e. works on two operand. This is also known
as Exclusive OR operator. Bitwise XOR takes
two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is
1 if the two bits are different.
~ (Bitwise NOT) : This is a unary operator i.e.
works on only one operand. Bitwise NOT
operator takes one number and inverts all bits
of it.
Bitwise Operators
<< (Bitwise Left Shift) : This is a binary
operator i.e. works on two operand. Bitwise Left
Shift operator takes two numbers, left shifts the
bits of the first operand, the second operand
decides the number of places to shift.
Input: First = 5, Second = 1
Explanation: Binary representation of 5 is
0101 . Therefore, bitwise << will shift the bits of
5 one times towards the left (i.e. 01010 )
Bitwise Operators
>> (Bitwise Right Shift) : This is also binary
operator i.e. works on two operand. Bitwise
Right Shift operator takes two numbers, right
shifts the bits of the first operand, the second
operand decides the number of places to shift.
Input: First = 5, Second = 1 Output: The bitwise
>> of both these value will be 2. Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
PHP Conditional Statements
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}
If ... Else...
If (condition)
<?php
{ If($user==“John”)
{
Print “Hello John.”;
Statements; }
Else
} {
Print “You are not John.”;
}
Else ?>
{
Statement;
No THEN in PHP
}
PHP Conditional Statements
The following example will output "Have a nice
weekend!" if the current day is Friday:
PHP Conditional Statements
Use the if....else statement to execute some code
if a condition is true and another code if a
condition is false.
PHP Conditional Statements
•
Using $$
$help = “hiddenVar”;
$$help = “hidden Value”;
echo $$help; // prints hidden Value
$$help = 10;
$help = $$help * $$help;
echo $help; // print 100