PHP New

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

PHP

PHP Introduction
• PHP started out as a small open source project that evolved as
more and more people found out how useful it was. Rasmus
Lerdorf unleashed the first version of PHP way back in 1994.
• PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
• PHP is a server side scripting language that is embedded in
HTML. It is used to manage dynamic content, databases,
session tracking, even build entire e-commerce sites.
• It is integrated with a number of popular databases, including
MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft
SQL Server.
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
Comments
// This is a comment
# This is also a comment
/* This is a comment
that is spread over
multiple lines */
• Do not nest multi-line comments
• // recommended over #
• All PHP code goes between php tag. A syntax of
PHP tag is given below:

<?php   
//your code here  
?> 
<!DOCTYPE>  
<html>  
<body>  
<?php  
echo "<h2>Hello First PHP</h2>";  
?>  
</body>  
</html>
• printing string
<?php  
echo "Hello by PHP echo";  
?>

• printing multi line string


<?php  
echo "Hello by PHP echo  
this is multi line  
text printed by   
PHP echo statement  
";  
?>
• printing escaping characters
<?php  
echo "Hello escape \"sequence\" characters";  
?>

• printing variable value


<?php  
$msg="Hello JavaTpoint PHP";  
echo "Message is: $msg";   
?> 
PHP Print
• PHP print statement can be used to print string,
multi line strings, escaping characters, variable,
array etc.
• Same as echo
PHP Variables
• A variable in PHP is a name of memory location that
holds data. A variable is a temporary storage that is
used to store data temporarily.
• In PHP, a variable is declared using $ sign followed
by variable name.
PHP Variable: Declaring string,
integer and float
<?php  
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str <br/>";  
echo "integer is: $x <br/>";  
echo "float is: $y <br/>";  
?>  
PHP Variable: Sum of two
variables
<?php  
$x=5;  
$y=6;  
$z=$x+$y;  
echo $z;  
?>

PHP Variable: case sensitive


<?php  
$color="red";  
echo "My car is " . $color . "<br>";  
echo "My house is " . $COLOR . "<br>";  
echo "My boat is " . $coLOR . "<br>";  
?>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are NOT case-sensitive.
PHP Constants
• PHP constants are name or identifier that can't be
changed during the execution of the script.
• PHP constants follow the same PHP variable rules.
For example, it can be started with letter or
underscore only.
• Conventionally, PHP constants should be defined in
uppercase letters.
• define(name, value, case-insensitive) 

<?php  
define("MESSAGE","Hello JavaTpoint PHP",true);
//not case sensitive  
echo MESSAGE;  
echo message;  
?> 
<?php  
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive  
echo MESSAGE;  
echo message;  
?> 
PHP Data Types
• 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
• Object
• NULL
• Resource
Literals..
• All strings must be enclosed in single of double
quotes: ‘Hello’ or “Hello”.
• Numbers are not in enclosed in quotes: 1 or 45 or
34.564
• Booleans (true/flase) can be written directly as
true or false.
• The PHP var_dump() function returns the data type and
value: <?php
$x = 5985;
var_dump($x);
?>
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);
?>
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 Operators
•Operators are used to operate on values. There are
four classifications of operators:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
PHP Arithmetic Operators
Operator Name Example Result
• PHP arithmetic
operators are used + Addition $x + $y Sum of $x and $y
with numeric values to
perform common - Subtraction $x - $y Difference of $x and $y
arithmetical
* Multiplication $x * $y Product of $x and $y
operations, such as
addition, subtraction, / Division $x / $y Quotient of $x and $y
multiplication etc.
Remainder of $x divided
% Modulus $x % $y by $y

Exponentiatio $x ** $y Result of raising $x to the


** $y'th power (Introduced
n in PHP 5.6)
1. <?php
$x = 10;
$y = 6;
echo $x + $y;
?>
PHP Assignment Operators
The PHP assignment
Assignm
operators are used ent
Same as... Description
with numeric values The left operand gets set to the value
to write a value to a x=y x=y of the expression on the right
variable.
x += y x=x+y Addition
The basic assignment
operator in PHP is x -= y x=x-y Subtraction
"=". It means that the
left operand gets set x *= y x=x*y Multiplication
to the value of the
assignment x /= y x=x/y Division
expression on the
right. x %= y x=x%y Modulus

2. <?php
$x = 10;
echo $x;
?>
Comparison Operators Operator Name Example Result

• Comparison
operators are used
== Equal $x == $y Returns true if $x is equal to $y

in logical statements === Identical $x === $y


Returns true if $x is equal to $y, and they are of
the same type

to determine
equality or != Not equal $x != $y Returns true if $x is not equal to $y

difference between
variables or values.
<> Not equal $x <> $y Returns true if $x is not equal to $y

Returns true if $x is not equal to $y, or they are


!== Not identical $x !== $y
not of the same type

3. <?php
$x = 100; > Greater than $x > $y Returns true if $x is greater than $y

$y = "100";
var_dump($x == $y); < Less than $x < $y Returns true if $x is less than $y

// returns true because values are equal


?> >= 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
Logical Operators
• Logical operators are used to determine
the logic between variables or values.
Operato
r Name Example Result

5. <?php and And $x and $y True if both $x and $y


are true
$x = 100;
$y = 50; or Or $x or $y
True if either $x or $y
is true
if ($x == 100 and $y == 50)
{ echo "Hello world!"; } True if either $x or $y
xor Xor $x xor $y
?> is true, but not both

True if both $x and $y


&& And $x && $y
are true

|| Or $x || $y True if either $x or $y
is true

! Not !$x True if $x is not true


PHP Increment / Decrement Operators

• The PHP increment operators are used to 4. <?php


$x = 10;
increment a variable's value. echo ++$x;
?>
• 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 String Operators
• PHP has two operators that are specially designed
for strings.
Operator Name Example Result
Concatenation of
. Concatenation $txt1 . $txt2 $txt1 and $txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to
assignment $txt1

6. <?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
PHP Array Operators

• The PHP array operators are used to compare


arrays.
Operator Name Example Result

+ Union $x + $y Union of $x and $y

Returns true if $x and $y have the same


== Equality $x == $y
key/value pairs

Returns true if $x and $y have the same


=== Identity $x === $y 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


7. <?php
$x = array("a" => "red", "b"
=> "green");
$y = array("c" => "blue", "d"
=> "yellow");
print_r($x + $y); // union of
$x and $y
?>
PHP Conditional Statements
• Very often when you write code, you want to
perform different actions for different decisions.
• You can use conditional statements in your code to
do this.
• if...else statement - use this statement if you want to
execute a set of code when a condition is true and
another if the condition is not true
• elseif statement - is used with the if...else statement to
execute a set of code if one of several condition are true
• Q1 & Q3
The Switch Statement
• If you want to select one of many blocks of code to
be executed, use the Switch statement.
• The switch statement is used to avoid long blocks of
if..elseif..else code.

• Q . The “date(“l”)” method returns the weekday as


a name between Sunday and Saturday. (Sunday,
Monday, Tuesday).Use the weekday to calculate
weekday name.
PHP Looping

• Looping statements in PHP are used to execute the same


block of code a specified number of times.
• Very often when you write code, you want the same block
of code to run a number of times. You can use looping
statements in your code to perform this.
• In PHP we have the following looping statements:
• while - loops through a block of code if and as long as a specified
condition is true (Q2)
• do...while - loops through a block of code once, and then repeats
the loop as long as a special condition is true (Q2)
• for - loops through a block of code a specified number of
times( write script for prints the text "Hello World!" five times) (Q4
&Q5)
• foreach - loops through a block of code for each element in an
array
The foreach Statement - Syntax

• The foreach statement is used to loop through


arrays.
• For every loop, the value of the current array
element is assigned to $value (and the array
pointer is moved by one) - so on the next loop,
you'll be looking at the next element.
foreach (array as value)
{
code to be executed;
}
• Q6
Create a PHP Function

• A function is a block of code that can be executed


whenever we need it.
• Creating PHP functions:
• All functions start with the word "function()“
• Name the function - It should be possible to understand
what the function does by its name. The name can start
with a letter or underscore (not a number)
• Add a "{" - The function code starts after the opening
curly brace
• Insert the function code
• Add a "}" - The function is finished by a closing curly
brace
<?php
function writeMyName()
{
echo "Marcus Oliver Graichen";
}
echo "Hello world!<br />";
echo "My name is ";
writeMyName();
echo ".<br />That's right, ";
writeMyName();
echo " is my name.";
?>
PHP Functions - Adding parameters

• Our first function writeMyName() is a very


simple function. It only writes a static string.
• To add more functionality to a function, we can
add parameters. A parameter is just like a
variable.
• You may have noticed the parentheses
(brackets!) after the function name, like:
writeMyName(). The parameters are specified
inside the parentheses.
<?php
function writeMyName($fname)
{
echo $fname . " Smith.<br />";
}
echo "My name is ";
writeMyName("John");
echo "My name is ";
writeMyName("Sarah");
echo "My name is ";
writeMyName("Smith");
?>
PHP Functions - Return values
• Functions can also be used to return values.
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
• Q10 & Q11
PHP Arrays
• An array can store one or more values in a single variable name.
• When working with PHP, sooner or later, you might want to
create many similar variables.
• Instead of having many similar variables, you can store the data
as elements in an array.
• Each element in the array has its own ID so that it can be easily
accessed.
• There are three different kind of arrays:
• Numeric array - An array with a numeric ID key
• Associative array - An array where each ID key is associated with a
value
• Multidimensional array - An array containing one or more arrays
Numeric Arrays
Loops
• A numeric array stores each element with a
numeric ID key.
• There are different ways to create a
numeric array.
• The ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
• Assign the ID key manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
Associative Arrays

• An associative array, each ID key is associated with


a value.
• 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.
• We use an array to assign ages to the different
persons:
$ages = array("Peter"=32, "Quagmire"=30, "Joe"=34);
Multidimensional Arrays
• In a multidimensional array, each element in the main
array can also be an array. And each element in the sub-
array can be an array, and so on.
• We create a multidimensional array, with automatically
assigned ID keys:
$families = array
( "Griffin"=> array (
"Peter",
"Lois",
"Megan“ ),
"Quagmire"=> array (
"Glenn” ),
"Brown"=> array(
"Cleveland",
"Loretta",
"Junior")
);

• Is Megan a part of the Griffin family?

• Q7 , Q8 & Q9

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy