SlideShare a Scribd company logo
PHP (BASICS)
• PHP Defination
• PHP Syntax
• PHP Comments
• PHPVariables
• ECHO and PRINT
• PHP Datatypes
• PHP Constents
• PHP Operators
P H P
• PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
What is a PHP File?
• PHP files have extension ".php"
WHAT CAN PHP DO?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
P H P S Y N T A X P H P C O M M E N T S
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
// Outputs a welcome message:
echo "Welcome Home!";
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
PHP VARIABLES
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
• Variable names are case-sensitive
Example- $x = 5;
$y = "John"
PHP VARIABLES SCOPE
The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:
• local
• global
• static
GLOBAL AND LOCAL SCOPE
• A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function.
Global Scope
<?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();
echo "<p>Variable x outside function is: $x</p>";
?>
Output - Variable x inside function is:
Variable x outside function is: 5
LOCAL SCOPE
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
Output - Variable x inside function is: 5
Variable x outside function is:
P H P E C H O A N D P R I N T S T A T E M E N T S
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.
P H P D ATA T Y P E S
Variables can store data of different types, and different data types can do
different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• NULL
PHP STRING
A string is a sequence of characters, like "Hello world!“.
<?php
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
?>
Output - string(12) "Hello world!"
string(12) "Hello world!"
P H P I N T E G E R
• An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
<?php
$x = 5985;
var_dump($x);
?>
Output - int(5985)
PHP FLOAT
• A float (floating point number) is a number with a decimal point or a number in exponential form.
• In the following example $x is a float.The PHP var_dump() function returns the data type and
value:
<?php
$x = 10.365;
var_dump($x);
?>
Output - float(10.365)
PHP BOOLEAN
A Boolean represents two possible states:TRUE or FALSE.
<html>
<body>
<?php
$x = true;
var_dump($x);
?>
</body>
</html>
Output - bool(true)
P H P A R R AY
• 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 CASTING
Change DataType
Casting in PHP is done with these statements:
(string) - Converts to data type String
(int) - Converts to data type Integer
(float) - Converts to data type Float
(bool) - Converts to data type Boolean
(array) - Converts to data type Array
(object) - Converts to data type Object
(unset) - Converts to data type NULL
P H P C O N S TA N T S
• Constants are like variables, except that once they are defined they cannot be
changed or undefined.
• A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
• A valid constant name starts with a letter or underscore (no $ sign before the constant
name)
Syntax:
define(name, value, case-insensitive);
P H P O P E R ATO R S
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators
PHP ARITHMETIC OPERATORS
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
PH P A S S I G N M E N T O P E R ATO R S
The PHP assignment operators are used with numeric values to write a value to
a variable
Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the
right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the
same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero,
depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.
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 Same as... 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 LOGICAL OPERATORS
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not
both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
P H P S T R I N G O P E R A T O R S
PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation
assignment
$txt1 .= $txt2 Appends $txt2 to $txt1
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
P H P C O N D I T I O N A L A S S I G N M E N T O P E R A T O R S
The PHP conditional assignment operators are used to set a value depending on
conditions:
Operator Name Example Result
?: Ternary $x
= expr1 ? expr2 : e
xpr3
Returns the value of $x.
The value of $x is expr2 if expr1 =
TRUE.
The value of $x is expr3 if expr1 =
FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x
is expr1 if expr1 exists, and is not
NULL.
If expr1 does not exist, or is NULL,
the value of $x is expr2.
PHP IF STATEMENTS
if statement - executes some code if one condition is true.
<?php
if (5 > 3) {
echo "Have a good day!";
}
?>
Output - Have a good day!
P H P I F. . . E L S E S TAT E M E N T S
The if...else statement executes some code if a condition is true and another code if that condition is
false.
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output - Have a good day!
I F. . . E L S E I F. . . E L S E S TAT E M E N T
The if...elseif...else statement executes different codes for more than two conditions.
<?php
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output - Have a good day!
N E S T E D I F
You can have if statements inside if statements, this is called nested if statements.
<?php
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
?>
Output - Above 10 but not above 20
P H P S W I T C H S T A T E M E N T
The switch statement is used to perform different actions based on different conditions.
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PH P LO O P S
• Loops are used to execute the same block of code again and again, as long as
a certain condition is true.
In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array
P H P W H I L E L O O P
The while loop - Loops through a block of code as long as the specified condition is true.
<?php
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
?>
Ouput - 12345
DO WHILE LOOP
The do...while loop - Loops through a block of code once, and then repeats the loop as long as the specified
condition is true.
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
Ouput - 12345
The for loop is used when you know how many times the script should run.
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Output - The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
F OR E AC H LO OP
The most common use of the foreach loop, is to loop through the items of an array.
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
?>
Output - red
green
blue
yellow
BREAK
The break statement can be used to jump out of a for loop.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
Ouput - The number is: 0
The number is: 1
The number is: 2
The number is: 3
C O N T I N U E
The continue statement stops the current iteration in the for loop and continue with the next.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Output- The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
F U N C T I O N S
PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.
PHP Built-in Functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a
specific task.
PHP User Defined Functions
Besides the built-in PHP functions, it is possible to create your own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
C R E AT E A F U N C T I O N
<?php
function myMessage() {
echo "Hello world!";
}
myMessage();
?>
Output- Hello world!
FUNCTION ARGUMENTS
Information can be passed to functions through arguments.An argument is just like a variable.
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Output - Jani Refsnes.
Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes.
DEFAULT ARGUMENT VALUE
The following example shows how to use a default parameter. If we call the function setHeight() without arguments
it takes the default value as argument:
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
Output - The height is : 350
The height is : 50
The height is : 135
The height is : 80
FUNCTI ONS - RE TURNI NG VALUES
To let a function return a value, use the return statement:
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
Output- 5 + 10 = 15
7 + 13 = 20
2 + 4 = 6
ARRAYS
An array stores multiple values in one single variable:
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
output- array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
P H P A R R A Y T Y P E S
there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Working With Arrays
In this tutorial you will learn how to work with arrays, including:
• Create Arrays
• Access Arrays
• Update Arrays
• Add Array Items
• Remove Array Items
• Sort Arrays
I N D E X E D A R R AY S
In indexed arrays each item has an index number.
By default, the first item has index 0, the second item has item 1, etc.
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
Output-array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota“
}
A S S O C I AT I V E A R R AY S
Associative arrays are arrays that use named keys that you assign to them.
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);
?>
Output - array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
M U L T I D I M E N S I O N A L A R R A Y S
A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However,
arrays more than three levels deep are hard to manage for most people.
Example-
Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
Output - Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
A R R AY F U N C T I O N S
• sort() - sort arrays in ascending order.
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output- BMW
Toyota
Volvo
• rsort() - sort arrays in descending order.
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output - Volvo
Toyota
BMW
• asort() - sort associative arrays in ascending order, according to the value.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ",Value=" . $x_value;
echo "<br>";
}
?>
Output- Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
• ksort() - sort associative arrays in ascending order, according to the key.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ",Value=" . $x_value;
echo "<br>";
}
?>
Output- Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
• arsort() - sort associative arrays in descending order, according to the value.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ",Value=" . $x_value;
echo "<br>";
}
?>
Output- Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
• krsort() - sort associative arrays in descending order, according to the key.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ",Value=" . $x_value;
echo "<br>";
}
?>
Output- Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
• To remove an existing item from an array, you can use the array_splice()
function.
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
var_dump($cars);
?>
Output- array(2) {
[0]=>
string(5) "Volvo"
[1]=>
string(6) "Toyota"
}
• Array_chunks() Splits an array into chunks of arrays.
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>
Output-
Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] =>
Toyota [1] => Honda ) [2] => Array ( [0] => Mercedes [1] => Opel
) )
• array_diff() Compare arrays, and returns the differences (compare values
only).
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
print_r($result);
?>
Output- Array ( [d] => yellow )
• array_filter()Filters the values of an array using a callback function.
<?php
function test_odd($var)
{
return($var & 1);
}
$a1=array(1,3,2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
Output- Array ( [0] => 1 [1] => 3 [3] => 3 )
• array_keys()Returns all the keys of an array.
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>
Output- Array ( [0] => Volvo [1] => BMW [2] => Toyota )
• array_map() Sends each value of an array to a user-made function,
which returns new values.
<?php
function myfunction($num)
{
return($num*$num);
}
$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>
Output - Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
• array_merge() Merges one or more arrays into one array.
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Ouput- Array ( [0] => red [1] => green [2] => blue [3] => yellow )
• array_pop() Deletes the last element of an array.
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Output - Array ( [0] => red [1] => green )
• array_push()Inserts one or more elements to the end of an array.
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Output- Array ( [0] => red [1] => green [2] => blue [3] => yellow )
• array_replace() Replaces the values of the first array with the values
from following arrays.
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>
Output- Array ( [0] => blue [1] => yellow )
• array_reverse() Returns an array in the reverse order.
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
Output- Array ( [c] => Toyota [b] => BMW [a] => Volvo )
• array_slice() Returns selected parts of an array.
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
Output- Array ( [0] => blue [1] => yellow [2] => brown )
• array_splice() Removes and replaces specified elements of an
array.
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>
Output- Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
• array_sum() Returns the sum of the values in an array.
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
Output- 45
• array_search() Searches an array for a given value and returns
the key.
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
Output- a
• array_shift() Removes the first element from an array, and returns
the value of the removed element.
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a)."<br>";
print_r ($a);
?>
Output- red
Array ( [b] => green [c] => blue )
• array_unshift() Adds one or more elements to the beginning of an
array.
<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>
Output-Array ( [0] => blue [a] => red [b] => green )
• array_values() Returns all the values of an array.
<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>
Output- Array ( [0] => Peter [1] => 41 [2] => USA )
• count() Returns the number of elements in an array.
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Output - 3
• in_array() Checks if a specified value exists in an array.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
Output- Match found
• key() Fetches a key from an array.
<?php
$people=array("Peter","Joe","Glenn","Cleveland");
echo "The key from the current position is: " . key($people);
?>
Output- The key from the current position is: 0
• array_change_key_case() Changes all keys in an array to lowercase or
uppercase.
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
print_r(array_change_key_case($age,CASE_UPPER));
?>
Output- Array ( [PETER] => 35 [BEN] => 37 [JOE] => 43 )
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
print_r(array_change_key_case($age,CASE_LOWER));
?>
Ouput - Array ( [peter] => 35 [ben] => 37 [joe] => 43 )
THANK
YOU
Ad

More Related Content

Similar to PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n (20)

Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401
lakshitakumar291
 
Unit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptxUnit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptx
AatifKhan84
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
PHP variables
PHP  variablesPHP  variables
PHP variables
Siddique Ibrahim
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
Yoeung Vibol
 
Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
Vineet Kumar Saini
 
Php
PhpPhp
Php
Vishnu Raj
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Php + my sql
Php + my sqlPhp + my sql
Php + my sql
Ashen Disanayaka
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam
 
Php basics
Php basicsPhp basics
Php basics
Jamshid Hashimi
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
yzebelle
 
PHP-Part1
PHP-Part1PHP-Part1
PHP-Part1
Ahmed Saihood
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
data type in php and its introduction to use
data type in php and its introduction to usedata type in php and its introduction to use
data type in php and its introduction to use
vishal choudhary
 
Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401Unit IV.pptx Server side scripting PHP IT3401
Unit IV.pptx Server side scripting PHP IT3401
lakshitakumar291
 
Unit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptxUnit-1 PHP Basic1 of the understanding of php.pptx
Unit-1 PHP Basic1 of the understanding of php.pptx
AatifKhan84
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
Open Gurukul
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
yzebelle
 
data type in php and its introduction to use
data type in php and its introduction to usedata type in php and its introduction to use
data type in php and its introduction to use
vishal choudhary
 

Recently uploaded (20)

AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Gojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service BusinessGojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service Business
XongoLab Technologies LLP
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdfProtect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
Protect HPE VM Essentials using Veeam Agents-a50012338enw.pdf
株式会社クライム
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Adobe Media Encoder Crack FREE Download 2025
Adobe Media Encoder  Crack FREE Download 2025Adobe Media Encoder  Crack FREE Download 2025
Adobe Media Encoder Crack FREE Download 2025
zafranwaqar90
 
Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??Serato DJ Pro Crack Latest Version 2025??
Serato DJ Pro Crack Latest Version 2025??
Web Designer
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Tools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google CertificateTools of the Trade: Linux and SQL - Google Certificate
Tools of the Trade: Linux and SQL - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025Wilcom Embroidery Studio Crack Free Latest 2025
Wilcom Embroidery Studio Crack Free Latest 2025
Web Designer
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
Download MathType Crack Version 2025???
Download MathType Crack  Version 2025???Download MathType Crack  Version 2025???
Download MathType Crack Version 2025???
Google
 
Best HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRMBest HR and Payroll Software in Bangladesh - accordHRM
Best HR and Payroll Software in Bangladesh - accordHRM
accordHRM
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
Ad

PHP PPT.pptxPHP PPT.pptxPHP PPT.pptxPHP n

  • 1. PHP (BASICS) • PHP Defination • PHP Syntax • PHP Comments • PHPVariables • ECHO and PRINT • PHP Datatypes • PHP Constents • PHP Operators
  • 2. P H P • PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. What is PHP? • PHP is an acronym for "PHP: Hypertext Preprocessor" • PHP is a widely-used, open source scripting language • PHP scripts are executed on the server • PHP is free to download and use What is a PHP File? • PHP files have extension ".php"
  • 3. WHAT CAN PHP DO? • PHP can generate dynamic page content • PHP can create, open, read, write, delete, and close files on the server • PHP can collect form data • PHP can send and receive cookies • PHP can add, delete, modify data in your database • PHP can be used to control user-access • PHP can encrypt data
  • 4. P H P S Y N T A X P H P C O M M E N T S <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html> // Outputs a welcome message: echo "Welcome Home!"; Multi-line Comments Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored.
  • 5. PHP VARIABLES • A variable starts with the $ sign, followed by the name of the variable • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores • Variable names are case-sensitive Example- $x = 5; $y = "John"
  • 6. PHP VARIABLES SCOPE The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: • local • global • static
  • 7. GLOBAL AND LOCAL SCOPE • A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. Global Scope <?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(); echo "<p>Variable x outside function is: $x</p>"; ?> Output - Variable x inside function is: Variable x outside function is: 5
  • 8. LOCAL SCOPE <?php function myTest() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } myTest(); // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ?> Output - Variable x inside function is: 5 Variable x outside function is:
  • 9. P H P E C H O A N D P R I N T S T A T E M E N T S 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.
  • 10. P H P D ATA T Y P E S Variables can store data of different types, and different data types can do different things. PHP supports the following data types: • String • Integer • Float (floating point numbers - also called double) • Boolean • Array • NULL
  • 11. PHP STRING A string is a sequence of characters, like "Hello world!“. <?php $x = "Hello world!"; $y = 'Hello world!'; var_dump($x); echo "<br>"; var_dump($y); ?> Output - string(12) "Hello world!" string(12) "Hello world!"
  • 12. P H P I N T E G E R • An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. Rules for integers: • An integer must have at least one digit • An integer must not have a decimal point • An integer can be either positive or negative • Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation <?php $x = 5985; var_dump($x); ?> Output - int(5985)
  • 13. PHP FLOAT • A float (floating point number) is a number with a decimal point or a number in exponential form. • In the following example $x is a float.The PHP var_dump() function returns the data type and value: <?php $x = 10.365; var_dump($x); ?> Output - float(10.365)
  • 14. PHP BOOLEAN A Boolean represents two possible states:TRUE or FALSE. <html> <body> <?php $x = true; var_dump($x); ?> </body> </html> Output - bool(true)
  • 15. P H P A R R AY • 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" }
  • 16. PHP CASTING Change DataType Casting in PHP is done with these statements: (string) - Converts to data type String (int) - Converts to data type Integer (float) - Converts to data type Float (bool) - Converts to data type Boolean (array) - Converts to data type Array (object) - Converts to data type Object (unset) - Converts to data type NULL
  • 17. P H P C O N S TA N T S • Constants are like variables, except that once they are defined they cannot be changed or undefined. • A constant is an identifier (name) for a simple value. The value cannot be changed during the script. • A valid constant name starts with a letter or underscore (no $ sign before the constant name) Syntax: define(name, value, case-insensitive);
  • 18. P H P O P E R ATO R S Operators are used to perform operations on variables and values. PHP divides the operators in the following groups: • Arithmetic operators • Assignment operators • Comparison operators • Increment/Decrement operators • Logical operators • String operators • Array operators • Conditional assignment operators
  • 19. PHP ARITHMETIC OPERATORS The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Operator Name Example Result + Addition $x + $y Sum of $x and $y - Subtraction $x - $y Difference of $x and $y * Multiplication $x * $y Product of $x and $y / Division $x / $y Quotient of $x and $y % Modulus $x % $y Remainder of $x divided by $y ** Exponentiation $x ** $y Result of raising $x to the $y'th power
  • 20. PH P A S S I G N M E N T O P E R ATO R S The PHP assignment operators are used with numeric values to write a value to a variable Assignment Same as... Description x = y x = y The left operand gets set to the value of the expression on the right x += y x = x + y Addition x -= y x = x - y Subtraction x *= y x = x * y Multiplication x /= y x = x / y Division x %= y x = x % y Modulus
  • 21. The PHP comparison operators are used to compare two values (number or string): Operator Name Example Result == Equal $x == $y Returns true if $x is equal to $y === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y <> Not equal $x <> $y Returns true if $x is not equal to $y !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type > Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y <=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.
  • 22. 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 Same as... 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
  • 23. PHP LOGICAL OPERATORS The PHP logical operators are used to combine conditional statements. Operator Name Example Result and And $x and $y True if both $x and $y are true or Or $x or $y True if either $x or $y is true xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true || Or $x || $y True if either $x or $y is true ! Not !$x True if $x is not true
  • 24. P H P S T R I N G O P E R A T O R S PHP has two operators that are specially designed for strings. Operator Name Example Result . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
  • 25. 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
  • 26. P H P C O N D I T I O N A L A S S I G N M E N T O P E R A T O R S The PHP conditional assignment operators are used to set a value depending on conditions: Operator Name Example Result ?: Ternary $x = expr1 ? expr2 : e xpr3 Returns the value of $x. The value of $x is expr2 if expr1 = TRUE. The value of $x is expr3 if expr1 = FALSE ?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x. The value of $x is expr1 if expr1 exists, and is not NULL. If expr1 does not exist, or is NULL, the value of $x is expr2.
  • 27. PHP IF STATEMENTS if statement - executes some code if one condition is true. <?php if (5 > 3) { echo "Have a good day!"; } ?> Output - Have a good day!
  • 28. P H P I F. . . E L S E S TAT E M E N T S The if...else statement executes some code if a condition is true and another code if that condition is false. <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> Output - Have a good day!
  • 29. I F. . . E L S E I F. . . E L S E S TAT E M E N T The if...elseif...else statement executes different codes for more than two conditions. <?php if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> Output - Have a good day!
  • 30. N E S T E D I F You can have if statements inside if statements, this is called nested if statements. <?php $a = 13; if ($a > 10) { echo "Above 10"; if ($a > 20) { echo " and also above 20"; } else { echo " but not above 20"; } } ?> Output - Above 10 but not above 20
  • 31. P H P S W I T C H S T A T E M E N T The switch statement is used to perform different actions based on different conditions. <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?>
  • 32. PH P LO O P S • Loops are used to execute the same block of code again and again, as long as a certain condition is true. In PHP, we have the following loop types: • while - loops through a block of code as long as the specified condition is true • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true • for - loops through a block of code a specified number of times • foreach - loops through a block of code for each element in an array
  • 33. P H P W H I L E L O O P The while loop - Loops through a block of code as long as the specified condition is true. <?php $i = 1; while ($i < 6) { echo $i; $i++; } ?> Ouput - 12345
  • 34. DO WHILE LOOP The do...while loop - Loops through a block of code once, and then repeats the loop as long as the specified condition is true. <?php $i = 1; do { echo $i; $i++; } while ($i < 6); ?> Ouput - 12345
  • 35. The for loop is used when you know how many times the script should run. <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?> Output - The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9 The number is: 10
  • 36. F OR E AC H LO OP The most common use of the foreach loop, is to loop through the items of an array. <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $x) { echo "$x <br>"; } ?> Output - red green blue yellow
  • 37. BREAK The break statement can be used to jump out of a for loop. <?php for ($x = 0; $x < 10; $x++) { if ($x == 4) { break; } echo "The number is: $x <br>"; } ?> Ouput - The number is: 0 The number is: 1 The number is: 2 The number is: 3
  • 38. C O N T I N U E The continue statement stops the current iteration in the for loop and continue with the next. <?php for ($x = 0; $x < 10; $x++) { if ($x == 4) { continue; } echo "The number is: $x <br>"; } ?> Output- The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9
  • 39. F U N C T I O N S PHP has more than 1000 built-in functions, and in addition you can create your own custom functions. PHP Built-in Functions PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task. PHP User Defined Functions Besides the built-in PHP functions, it is possible to create your own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.
  • 40. C R E AT E A F U N C T I O N <?php function myMessage() { echo "Hello world!"; } myMessage(); ?> Output- Hello world!
  • 41. FUNCTION ARGUMENTS Information can be passed to functions through arguments.An argument is just like a variable. <?php function familyName($fname) { echo "$fname Refsnes.<br>"; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?> Output - Jani Refsnes. Hege Refsnes. Stale Refsnes. Kai Jim Refsnes. Borge Refsnes.
  • 42. DEFAULT ARGUMENT VALUE The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument: <?php function setHeight($minheight = 50) { echo "The height is : $minheight <br>"; } setHeight(350); setHeight(); setHeight(135); setHeight(80); ?> Output - The height is : 350 The height is : 50 The height is : 135 The height is : 80
  • 43. FUNCTI ONS - RE TURNI NG VALUES To let a function return a value, use the return statement: <?php function sum($x, $y) { $z = $x + $y; return $z; } echo "5 + 10 = " . sum(5,10) . "<br>"; echo "7 + 13 = " . sum(7,13) . "<br>"; echo "2 + 4 = " . sum(2,4); ?> Output- 5 + 10 = 15 7 + 13 = 20 2 + 4 = 6
  • 44. ARRAYS An array stores multiple values in one single variable: <?php $cars = array("Volvo", "BMW", "Toyota"); var_dump($cars); ?> output- array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
  • 45. P H P A R R A Y T Y P E S there are three types of arrays: • Indexed arrays - Arrays with a numeric index • Associative arrays - Arrays with named keys • Multidimensional arrays - Arrays containing one or more arrays Working With Arrays In this tutorial you will learn how to work with arrays, including: • Create Arrays • Access Arrays • Update Arrays • Add Array Items • Remove Array Items • Sort Arrays
  • 46. I N D E X E D A R R AY S In indexed arrays each item has an index number. By default, the first item has index 0, the second item has item 1, etc. <?php $cars = array("Volvo", "BMW", "Toyota"); var_dump($cars); ?> Output-array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota“ }
  • 47. A S S O C I AT I V E A R R AY S Associative arrays are arrays that use named keys that you assign to them. <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); var_dump($car); ?> Output - array(3) { ["brand"]=> string(4) "Ford" ["model"]=> string(7) "Mustang" ["year"]=> int(1964) }
  • 48. M U L T I D I M E N S I O N A L A R R A Y S A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. Example- Name Stock Sold Volvo 22 18 BMW 15 13 Saab 5 2 Land Rover 17 15
  • 49. <?php $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>"; ?> Output - Volvo: In stock: 22, sold: 18. BMW: In stock: 15, sold: 13. Saab: In stock: 5, sold: 2. Land Rover: In stock: 17, sold: 15.
  • 50. A R R AY F U N C T I O N S • sort() - sort arrays in ascending order. <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); $clength = count($cars); for($x = 0; $x < $clength; $x++) { echo $cars[$x]; echo "<br>"; } ?> Output- BMW Toyota Volvo
  • 51. • rsort() - sort arrays in descending order. <?php $cars = array("Volvo", "BMW", "Toyota"); rsort($cars); $clength = count($cars); for($x = 0; $x < $clength; $x++) { echo $cars[$x]; echo "<br>"; } ?> Output - Volvo Toyota BMW
  • 52. • asort() - sort associative arrays in ascending order, according to the value. <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); asort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ",Value=" . $x_value; echo "<br>"; } ?> Output- Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43
  • 53. • ksort() - sort associative arrays in ascending order, according to the key. <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); ksort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ",Value=" . $x_value; echo "<br>"; } ?> Output- Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35
  • 54. • arsort() - sort associative arrays in descending order, according to the value. <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); arsort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ",Value=" . $x_value; echo "<br>"; } ?> Output- Key=Joe, Value=43 Key=Ben, Value=37 Key=Peter, Value=35
  • 55. • krsort() - sort associative arrays in descending order, according to the key. <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); krsort($age); foreach($age as $x => $x_value) { echo "Key=" . $x . ",Value=" . $x_value; echo "<br>"; } ?> Output- Key=Peter, Value=35 Key=Joe, Value=43 Key=Ben, Value=37
  • 56. • To remove an existing item from an array, you can use the array_splice() function. <?php $cars = array("Volvo", "BMW", "Toyota"); array_splice($cars, 1, 1); var_dump($cars); ?> Output- array(2) { [0]=> string(5) "Volvo" [1]=> string(6) "Toyota" }
  • 57. • Array_chunks() Splits an array into chunks of arrays. <?php $cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel"); print_r(array_chunk($cars,2)); ?> Output- Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] => Toyota [1] => Honda ) [2] => Array ( [0] => Mercedes [1] => Opel ) )
  • 58. • array_diff() Compare arrays, and returns the differences (compare values only). <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"green","g"=>"blue"); $result=array_diff($a1,$a2); print_r($result); ?> Output- Array ( [d] => yellow )
  • 59. • array_filter()Filters the values of an array using a callback function. <?php function test_odd($var) { return($var & 1); } $a1=array(1,3,2,3,4); print_r(array_filter($a1,"test_odd")); ?> Output- Array ( [0] => 1 [1] => 3 [3] => 3 )
  • 60. • array_keys()Returns all the keys of an array. <?php $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander"); print_r(array_keys($a)); ?> Output- Array ( [0] => Volvo [1] => BMW [2] => Toyota )
  • 61. • array_map() Sends each value of an array to a user-made function, which returns new values. <?php function myfunction($num) { return($num*$num); } $a=array(1,2,3,4,5); print_r(array_map("myfunction",$a)); ?> Output - Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
  • 62. • array_merge() Merges one or more arrays into one array. <?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_merge($a1,$a2)); ?> Ouput- Array ( [0] => red [1] => green [2] => blue [3] => yellow )
  • 63. • array_pop() Deletes the last element of an array. <?php $a=array("red","green","blue"); array_pop($a); print_r($a); ?> Output - Array ( [0] => red [1] => green )
  • 64. • array_push()Inserts one or more elements to the end of an array. <?php $a=array("red","green"); array_push($a,"blue","yellow"); print_r($a); ?> Output- Array ( [0] => red [1] => green [2] => blue [3] => yellow )
  • 65. • array_replace() Replaces the values of the first array with the values from following arrays. <?php $a1=array("red","green"); $a2=array("blue","yellow"); print_r(array_replace($a1,$a2)); ?> Output- Array ( [0] => blue [1] => yellow )
  • 66. • array_reverse() Returns an array in the reverse order. <?php $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota"); print_r(array_reverse($a)); ?> Output- Array ( [c] => Toyota [b] => BMW [a] => Volvo )
  • 67. • array_slice() Returns selected parts of an array. <?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,2)); ?> Output- Array ( [0] => blue [1] => yellow [2] => brown )
  • 68. • array_splice() Removes and replaces specified elements of an array. <?php $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("a"=>"purple","b"=>"orange"); array_splice($a1,0,2,$a2); print_r($a1); ?> Output- Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )
  • 69. • array_sum() Returns the sum of the values in an array. <?php $a=array(5,15,25); echo array_sum($a); ?> Output- 45
  • 70. • array_search() Searches an array for a given value and returns the key. <?php $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_search("red",$a); ?> Output- a
  • 71. • array_shift() Removes the first element from an array, and returns the value of the removed element. <?php $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_shift($a)."<br>"; print_r ($a); ?> Output- red Array ( [b] => green [c] => blue )
  • 72. • array_unshift() Adds one or more elements to the beginning of an array. <?php $a=array("a"=>"red","b"=>"green"); array_unshift($a,"blue"); print_r($a); ?> Output-Array ( [0] => blue [a] => red [b] => green )
  • 73. • array_values() Returns all the values of an array. <?php $a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA"); print_r(array_values($a)); ?> Output- Array ( [0] => Peter [1] => 41 [2] => USA )
  • 74. • count() Returns the number of elements in an array. <?php $cars=array("Volvo","BMW","Toyota"); echo count($cars); ?> Output - 3
  • 75. • in_array() Checks if a specified value exists in an array. <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn", $people)) { echo "Match found"; } else { echo "Match not found"; } ?> Output- Match found
  • 76. • key() Fetches a key from an array. <?php $people=array("Peter","Joe","Glenn","Cleveland"); echo "The key from the current position is: " . key($people); ?> Output- The key from the current position is: 0
  • 77. • array_change_key_case() Changes all keys in an array to lowercase or uppercase. <?php $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); print_r(array_change_key_case($age,CASE_UPPER)); ?> Output- Array ( [PETER] => 35 [BEN] => 37 [JOE] => 43 )
  翻译: