Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
75 views

PHP Basic

Uploaded by

belinha1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

PHP Basic

Uploaded by

belinha1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

PHP#Language

Prof.#Dr.#Carlos#Alves
1
PHP#Basic

PHP#HTML#Forms

PHP#Sessions/Cookies PHP

PHP#and#MySQL

PHP#Advanced
2
• Introduction
• Syntax
• Variables
• Constants
• Print
• Data#Types
PHP#Basic • Operators
• If
• Switch
• Strings
• Arrays
• Loops
• Functions
Foto%de%Clay Leconey na%Unsplash% 3
• PHP stands for Hypertext Preprocessor. PHPTBasic
• PHP is an open source server4side scripting language
• Dynamically generated web pages
• Free
• PHP is a hybrid of Perl, Java and C
• Created by Rasmus Lerdorf in 1994.

• PHP scripts are executed on the server


• The result is sent to the web browser as HTML
• PHP can be integrated with the MySQL, PostgreSQL, Oracle, Microsoft SQL Server, Sybase, etc.

PopularTsitesTusing PHP
Facebook.com
Wikipedia.org
Wordpress.org
PHP is used by 77.5% of all the websites whose server4side programming Pinterest.com
language Vimeo.com
(2023/04/17 https://w3techs.com/technologies/details/pl4php) Wordpress.com
Mozilla.org
Europa.eu
Tumblr.com
Digicert.com
4
PHP#Basic
PHP#Can#Do#:
• Generate pages and files#
dynamically
• Create,#open,#read,#write and Advantages of PHP#[https://www.tutorialrepublic.com/phpHtutorial/]:
close files#on the server • Easy to'learn: PHP'is easy to'learn and use.'For'beginner
• Collect data#from a#web#form programmers who just started out'in'web'development,'PHP'
such as#user information,#email,# is often considered as'the preferable choice of language to'
phone no,#etc learn
• Send emails#to#the users of your • Open'source: PHP'is an open@source project.'It is developed
website and maintained by a'worldwide community of developers
• Send and receive cookies#to#track who make its source code freely available to'download'and
the visitor of your website use
• Store,#delete,#and modify • Portability: PHP'runs'on various platforms such as'Microsoft'
information in#your database Windows,'Linux,'Mac'OS, etc.'and it is compatible with almost
• Restrict unauthorized access to#a# all servers'used today such Apache,'IIS, etc
website • Fast Performance: Scripts'written in'PHP'usually execute'or
• Encrypt data runs'faster than those written in'other scripting languages like
• Send and receive cookies ASP,'Ruby,'Python,'Java,'etc
• Vast Community: Since PHP'is supported by the worldwide
community,'finding help or documentation related to'PHP'
online'is extremely easy.

5
PHPABasic
Why PHP?

• runs&on various platforms (Windows,&Linux,&Unix,&Mac&OS&X,&etc.)


• is compatible with almost all servers&used today (Apache,&IIS,&etc.)
• supports a&wide range&of databases
• is free
• official PHP&resource:&www.php.net
• is easy to&learn and runs&efficiently on the server&side

• Error Handling
• Supports stricter Type Declarations for function arguments
• Supports new operators (like the spaceship operator: <=>)

6
• PHP code editable by any texto editor PHPIBasic
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP can be embedded within a normal HTML web page
• Inside your HTML document you can write the PHP statements
• PHP files have extension ".php"

<!DOCTYPEIhtml>
<html>
<body>

<?php
echo "Hello World,Ithis my first PHPIscript!";
?>

</body>
</html>I

7
• Install Wampserver or XAMPP, or other
• Create web applications with Apache PHP>Basic
• MySQL database
• Place them in>your web>directory,>and the server>will automatically parse>them for>you
• You do>not need to>compile>anything or install any extra>tools

hello.php

<!DOCTYPE>html>
<html>
<body> C:\xamp\htdocs\lpi
<?php
echo "Hello World,>this my first PHP>script!";
?>

</body>
</html>>

http://localhost/lpi/hello.php
8
PHP3Basic

Insert PHP code into HTML:

<?3
echo (“Olá Mundo3<br>");3
?>3

<script3language="php">
echo(“Olá Mundo<br>”);
</script>3

<%3
<?php echo (“Olá Mundo<br>");3
echo (“Olá Mundo<br>");3 %>3
?>3

9
PHP1Basic

<?php
PHP Comments: /*1this is a1mul67line
comment */1
echo(“Olá Mundo\n");1
?>1

/*1*/1(type c)

//1(type c++) <?php


//1this is a1one line comment
echo(“Olá Mundo\n");1
#1(type shell do1Unix)11 ?>1

<?php
#1this is a1one line comment
echo(“Olá Mundo\n");1
?>1

10
PHP3Basic

<?php
Case Sensitivity in PHP: //3Assign value to3variable
$name =3”John";3
//3Try to3print3variable value
echo "The name is "3.3$name .3"<br>";3
echo "The Name is "3.3$Name .3"<br>";3
• Variable names in3PHP3are3caseKsensiLve.3As3a3 echo "The NAME3is "3.3$NAME3.3"<br>";3
result the variables $name,3$Name and $NAME3 ?>
are3treated as3three different variables

• Both3funcLons geQype()3and GETTYPE()3gives the


same output33 <?php
$name =3”John";3

//3Get the type of a3variable


echo gettype($name)3.3"<br>";3
echo GETTYPE($name)3.3"<br>";
?>3

11
PHP,Basic

PHP Variables:
• A,variable does,not need to,be declared before adding a,value to,it
• PHP,automatically associates a,data,type to,the variable
• The assignment operator (=),used to,assign value to,a,variable
• 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 alphaCnumeric characters and underscores (ACz,,0C9,,and _,)
• Variable names are,caseCsensitive ($age,and $AGE,are,two different variables)
<?php
$var =,"Bob";,
$Var,=,"Joe";,
echo,"$var,,$Var";,//,Display,"Bob,,Joe",
$4site,=,'not,yet';,//,NOT,valid;,starts,with,digit,
$_4site,=,'not,yet';,//,valid;,starts,with,underline,
$täyte =,'mansikka';,//,valid;,'ä',is,ASCII,228
?>, 12
PHP/Basic

PHP Constants:

• A/constant is a/name or an idenMfier for/a/fixed value


• Constant are/like variables,/except that once they are/defined
• Constants are/defined using PHP's define()/funcMon,/which accepts two
arguments:/the name of the constant,/and its value
• Name of constants must/follow the same rules/as/variable/names
• the $/prefix is not required for/constant names

<?php
///Define/the constant
define(”LPI",/”PHP/Language");/
///Use/the constant
echo 'Thank you for/learning G '/./LPI;/
?>

13
PHP2Basic

PHP echo statement:

• The echo statement can2output2one or more2strings


• The echo statement can2display2anything that can2be displayed to2the browser,2
such as2string,2numbers,2variables values,2the results of expressions
• Since echo is a2language construct,2not a2funcOon,2it can2use2it without
parentheses e.g.2echo or echo()

<?php
$php =2"2PHP2Language";
$txt =2“www.ipcb.pt/estcb/escola@superior@de@tecnologia2";
$num2=25;

echo "<h2>"2.2$php .2"</h2>";


echo "Study “.2$php.2“2at "2.2$txt .2"<br>";
echo ($num)2;
?>

14
PHP2Basic

PHP echo statement:

• The echo statement can2output2one or more2strings


• The echo statement can2display2anything that can2be displayed to2the browser,2
such as2string,2numbers,2variables values,2the results of expressions
• Since echo is a2language construct,2not a2function,2it can2use2it without
parentheses e.g.2echo or echo()
• The echo statement can2display2HTML2code

<?php
$php =2"2PHP2Language";
$txt =2“www.ipcb.pt/estcb/escola@superior@de@tecnologia2";
$num2=25;

echo "<h2>"2.2$php .2"</h2>";


echo "Study “.2$php.2“2at "2.2$txt .2"<br>";
echo ($num)2;
echo "localhost",2"root",2"",2"iset";
?>
15
PHP2Basic

PHP print statement:

• echo and print2are2are2both used to2output2data2to2the screen


• Both2echo and print2statement works exactly the same way ...
• ...2except that the print2statement can2only output2one string,2and always
returns 1
• The echo statement considered marginally faster than the print2statement

<?php
$php =2"2PHP2Language";
$txt =2“www.ipcb.pt/estcb/escolaAsuperiorAdeAtecnologia2";
$num2=25;

print2"<h2>"2.2$php .2"</h2>";
print2"Study “.2$php.2“2at "2.2$txt .2"<br>";
print2($num)2;
?>
16
PHP+Basic

PHP data types:

• The values assigned to+a+PHP+variable may be of different data+types


• PHP+automatically associates a+data+type to+the variable
• PHP+is a+Loosely Typed Language (did not have to+tell PHP+which data+type the variable is)
• In+PHP+7,+type declarations were added
• PHP+supports total+eight primitive data+types:+
• Integer
• String
• Float (floaEng point numbers <=> also called double)
• Boolean
• Array
• Object <?php
• NULL $n1+=+123;+//+decimal+number
• Resource $n2+=+V123;+//+a+negaEve+number
$n3+=+0x1A;+//+hexadecimal
$n4+=+0123;+//+octal+number
?>

17
PHP1Basic

PHP data types (Integer):


• 2,1256,19256,110358,191795671are1integers
• An integer data1type is a1non9decimal1number
• Between92.147.483.6481and 2.147.483.6471in1321bit1systems
• Between992233720368547758081and 92233720368547758071in1641bit1systems
• An integer must1have at least one digit
• An integer must1not have a1decimal1point
• An integer can1be either posiKve1or negaKve
• Integers can1be specified in:1decimal1(base110),1hexadecimal1(169based19 prefixed with
0x),1octal1(89based19 prefixed with 0),1or binary (base12)1notaKon

<?php
$n11=1123;1//1decimal1number
$n21=19123;1//1a1negative1number
$n31=10x1A;1//1hexadecimal
$n41=10123;1//1octal1number
$n51=10b100111;1//1binary number
?>

18
PHP1Basic

PHP data types (Integer):

• predefined constants for1integers:


• PHP_INT_MAX,- The largest integer supported
• PHP_INT_MIN,- The smallest integer supported
• PHP_INT_SIZE,- The size of an integer in,bytes

• functions to1check if the type of a1variable is integer:


• is_int()
• is_integer(),- alias,of is_int()
• is_long(),- alias,of is_int()

19
PHP-Basic

PHP data types (Floating Point Numbers or Doubles):

• Floating point numbers,-or "floats",-or "doubles",-or "real-numbers")-


• Are-decimal-or fractional numbers
• With a-decimal-point or a-number in-exponential-form
• 2.0,-256.4,-10.358,-7.64E+5,-5.56EM5-are-floats
• Can-store a-value up to-1.7976931348623E+308-(platform dependent)-

<?php
$n1-=-112.234;-
$n2-=-12.3e4;-
$n3-=-3EM10;
?>

20
PHP-Basic

PHP data types (Floating Point Numbers or Doubles):

• predefined constants for-floats:


• PHP_FLOAT_MAX - The largest representable floating point number
• PHP_FLOAT_MIN - The smallest representable positive floating point number
• PHP_FLOAT_DIG - The number of decimal digits that can be rounded into a float and back without precision loss
• PHP_FLOAT_EPSILON - The smallest representable positive number x, so that x + 1.0 != 1.0

• func8ons to-check if the type of a-variable is float:


• is_float()
• is_double() - alias of is_float()

21
PHP1Basic

PHP data types (Boolean):

• Only two possible values:1either 11(true)1or 01(false)

<?php
$x1=1true;
$y1=1false;
?>

22
PHP2Basic

PHP data types (Numbers):


PHP2Infinity
• A2numeric value that is larger than PHP_FLOAT_MAX2is considered infinite
• funcGons to2check if a2numeric value is finite or infinite:
• is_finite()
• is_infinite()

PHP2Nan
• NaN stands2for2Not a2Number.
• NaN is used for2impossible mathemaGcal operaGons
• funcGons to2check if a2value is not a2number:
• is_nan()
• var_dump()3func6on returns the data3type and value

23
PHP7Basic

PHP data types (Numerical Strings):

• The PHP7is_numeric()7func=on can7be used to7find whether a7variable is numeric


• The func=on returns true if the variable is a7number or a7numeric string,7false7
otherwise
<?php
$n7=7123;
var_dump(is_numeric($n));77//7Displays7bool(true)7

$n7=7"123";
var_dump(is_numeric($n));7//7Displays7bool(true)7

$n7=7"123.45"7+7100;
var_dump(is_numeric($n));7//7Displays7bool(true)7

$n7=7"Hello";
var_dump(is_numeric($n));7//7Displays7bool(false)7
?>
24
PHP8Basic

PHP data types (Cas,ng String and Float to Integer):

• The (int),8(integer),8or intval()8func,ons are8used to8convert a8value to8an integer

<?php
$x8=812345.678;
$foat_int_cast =8(int)$x;8//8Cast8float to8int
echo $float_int_cast;

$x8=8"12345";
$str_int_cast =8(int)$x;8//8Cast8string to8int
echo $str_int_cast;
?>8

25
PHP/Basic

PHP data types (Arrays):

• An array stores multiple values in/one single/variable


• A/variable that can/hold more/than one value at a/time
• Aggregate a/series/of related items together
• An array is defined as/an indexed collection of data/ <?php
values $colors =/array("Red",/"Green",/"Blue");
• Each index (or key)/of an array is unique ... $color_codes =/array(/
• ...//and references a/corresponding value "Red"/=>/"#ff0000",/
"Green"/=>/"#00ff00",/
"Blue"/=>/"#0000ff"/);
$cars =/array(”Audi","Bmw",”Mercedes");
<?php ?>
$a[0]/=/"abc";/
$a[1]/=/"def";/ <?php
$a[]/=/"olá";////$a[2]/==/"olá"/
$b["foo"]/=/13;
?>/ $a[]/=/"mundo";////$a[3]/==/"mundo"
?>/

26
PHP5Basic

PHP data types (multi/dimensional arrays): <?php


$f5=5123;

$a[1]5=5$f;
• Arrays currently act as5hash tables (associa;ve arrays)5
$a["foo"]5=5$f;5
and indexed arrays (vectors)

$a[1][0]5=5$f;5

<?php
$a[3]['bar']5=5'Bob’; $a["foo"][2]5=5$f;5
echo5" This won't work :5$a[3][bar]";5 $a[3]["bar"]5=5$f;5
$a["foo"][4]["bar"][0]5=5$f;
echo5" This will work :5{$a[3][bar]}5"; ?>5
echo5" This will work :"5.5$a[3][bar];
?>5
27
PHP6Basic
<?php
$a6=6array("apple"6=>6array(6
PHP data types (mul./dimensional arrays):
"color"6=>6"red",6
"taste"6=>6"sweet",6
• Arrays currently act as6hash tables "shape"6=>6"round"6),
(associative arrays)6and indexed
arrays (vectors) "orange"6=>6array(6
"color"6=>6"orange",6
<?php
"taste"6=>6"acidic",6
$a6=6array6(
<?php "shape"6=>6"round"6),6
$a["cor"]6=6”red";6 "cor"6=>6"vermelho",6
"banana"6=>6array(6
$a["sabor"]6=6”sweet";6 "sabor"6=>6"doce",6
"color"6=>6"yellow",6
$a["forma"]6=6”round";6 "forma"6=>6"redondo",6
"taste"6=>6"doughy",6
$a["nome"]6=6”apple";6 "nome"6=>6"maçã",6
"shape"6=>6"cylindrical"6)6
$a[3]6=64;6 36=>646
);6
?>6 );
echo6$a["apple"]["taste"];6#6show6"sweet"6
?>6
?>6 28
PHP1Basic

PHP data types (Objects):


• A1class is a1template for1objects,1and an
object is an instance of a1class <?php
• If you create a1__construct()1function,1 class car {
PHP1will automatically call this function public $brand;
public $model;
when you create an object from a1class public $color;
public funcPon __construct($brand,1$model,1$color)1{
<?php $thisM>brand =1$brand;
//1Class definition $thisM>model =1$model;
class greeting{ $thisM>color1=1$color;
//1properties }
public $str =1"Hello World!"; public funcPon message()1{
//1methods return "My car is a1"1.1$thisM>brand .1"1model "1.1$thisM
public function show_greeting(){ >model .1"1with the color1"1.1$thisM>color1.1"!";
return $thisM>str; }
} }
}
//1Create object from class $myCar =1new car("BMW",1"Series12",1"black");
$message =1new greeting; echo $myCarM>message();
echo $messageM>show_greeting(); ?>
?>
29
PHP0Basic

PHP data types (NULL):

• Null is a0special data0type which can0have only one value:0NULL


• A0variable of data0type NULL0is a0variable that has no0value assigned to0it
• $var10=0NULL0and $var20=0""0are0NOT0the same
• $var10has null value
• $var20indicates no0value assigned

<?php
$str =0"Hello World!";0
echo "$str <br>";
$str =0NULL;
echo "$str <br>";
?>

30
PHP2Basic

PHP data types (Resource):

• A2resource is a2special variable that holds a2reference to2an external resource (file2
or database)

<?php
$file_handle =2fopen("my_file.txt",2"r");

$conn =2mysqli_connect("localhost",2"root",2"");
?>

31
PHP2Basic

PHP data types (String):

• Strings are2sequences of characters,2where every character is the same as2a2byte


• String can2hold letters,2numbers,2and special characters
• Up to22GB2(21474836472bytes2maximum)
• String is to2enclose it in2single2quotes (e.g.2‘LPI!’)
• Can2also use2double quotes (”LPI!")

<?php
$str12=2'Hello!';2
echo $str12.2"<br>";2
$str22=2"Hello class!";2
echo $str22.2"<br>";2
$str32=2'Hello,2I\’m2here.';2
echo $str3;
?>

32
PHP2Basic

PHP data types (String):

• Strings enclosed in2single7quotes are2treated almost literally


• Strings delimited by the double quotes replaces variables with the string
representa?ons of their values
• Interpret especially certain escape2sequences
• \n2is replaced by the newline character
• \r2is replaced by the carriage7return character
• \t2is replaced by the tab character
• \$2is replaced by the dollar sign itself
<?php • \"2is replaced by a2single2double7quote
$my_num =212345;2 • \\ is replaced by a2single2backslash
echo "Hello,2$my_num!<br>"; //2Displays:2Hello 12345!2
echo 'Hello,2$my_num!<br>';2 //2Displays:2Hello,2$my_num!2
echo 'Hello\tWorld!';2 //2Displays:2Hello\tWorld!2
echo "Hello\tWorld!";2 //2Displays:2Hello World!2
echo 'I\'m2OK!'; //2Displays:2I´m OK!2
?>

33
PHP2Basic

PHP data types (String):

• strlen()2func8on is used to2calculate the number of characters inside a2string


• str_word_count()2func8on counts the number of words in2a2string
• str_replace()2replaces all occurrences of the search text within the target2string
• strrev()2func8on reverses2a2string
• strcmp() binary comparison of two string (case2sensi8ve)

• addcslashes() addslashes() bin2hex() chop() chr() chunk_split() convert_cyr_string()


convert_uudecode() convert_uuencode() count_chars() crc32() crypt() echo() explode() fprinD()
get_html_transla8on_table() hebrev() hex2bin() html_en8ty_decode() htmlen88es()
htmlspecialchars_decode() htmlspecialchars() implode() join() lcfirst() levenshtein() localeconv() ltrim()
md5() md5_file() metaphone() nl_langinfo() nl2br() number_format() ord() parse_str() print() prinD()
quoted_printable_decode() quoted_printable_encode() quotemeta() rtrim() setlocale() sha1()
sha1_file() similar_text() soundex() sprinD() sscanf() str_getcsv() str_ireplace() str_pad() str_repeat()
str_replace() str_rot13() str_shuffle() str_split() str_word_count() strcasecmp() strchr() strcmp() strcoll()
strcspn() strip_tags() stripcslashes() stripos() stripslashes() stristr() strlen() strnatcasecmp() strnatcmp()
strncasecmp() strncmp() strpbrk() strpos() strrchr() strrev() strripos() strrpos() strspn() strstr() strtok()
strtolower() strtoupper() strtr() substr() substr_compare() substr_count() substr_replace() trim()
ucfirst() ucwords() vfprinD() vprinD() vsprinD() wordwrap()
34
PHP0Basic

PHP data types (Constant):

• A0constant is an iden5fier (name)0for0a0simple value


• The value cannot be changed during the script
• A0valid constant name starts with a0leBer or underscore (no0$0sign before the constant name)
• To0create a0constant,0use0the define()0func5on

Note: Unlike variables,0constants are0automa5cally global0across the en5re script

<?php
define(name,0value,0case*insensitive) define("PHP",0"Welcome to0PHP0language!");
echo PHP;
define("GREETING",0"0Welcome to0PHP0language!",0true);
• name:0Specifies the name of the constant echo php;
• value:0Specifies the value of the constant ?>0
• case*insensi-ve:0Specifies whether the
constant name should be caseTinsensi5ve.0
Default is false
35
PHP0Basic

PHP data types (Operators):

Arithmetic Operators <?php


• The arithmetic operators are0used to0 $n10=011;0
perform arithmetical operations $n2=05;0
echo ($n10+0$n2);0
echo 2*$n10+0$n2;
?>

Operator Description Example Result


+ Addition $x,+,$y Sum,of,$x,and,$y
3 Subtraction $x,3 $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
36
PHP0Basic

PHP data types (Operators): <?php


$n10=011;0
$n2=05;0
Assignment Operators $n30=0$n1++;
$n40=0++$n2;
• The assignment operators are0used to0
echo $n1."<br"";0
assign values to0variables echo $n2;
?>

Operator Description Example Same As


= Assign $x+=+$y $x+=+$y
+= Add+and+assign $x++=+$y $x+=+$x+++$y
0= Subtract+and+assign $x+0=+$y $x+=+$x+0 $y
*= Multiply+and+assign $x+*=+$y $x+=+$x+*+$y
/= Divide+and+assign+quotient $x+/=+$y $x+=+$x+/+$y
%= Divide+and+assign+modulus $x+%=+$y $x+=+$x+%+$y
= Assign $x+=+$y $x+=+$y
37
PHP0Basic

PHP data types (Operators): <?php


$n10=011;0
$n2=05;0
Assignment Operators $n30+=0$n1;
$n40*=0$n2;
• The assignment operators are0used to0
echo $n3."<br"";0
assign values to0variables echo $n4;
?>

Operator Description Example Same As


= Assign $x+=+$y $x+=+$y
+= Add+and+assign $x++=+$y $x+=+$x+++$y
0= Subtract+and+assign $x+0=+$y $x+=+$x+0 $y
*= Multiply+and+assign $x+*=+$y $x+=+$x+*+$y
/= Divide+and+assign+quotient $x+/=+$y $x+=+$x+/+$y
%= Divide+and+assign+modulus $x+%=+$y $x+=+$x+%+$y
= Assign $x+=+$y $x+=+$y
38
PHP0Basic

PHP data types (Operators):


Comparison Operators
• The comparison operators are0used to0
compare0two Boolean values

<?php
$n10=011;0$n20=05;0$n30=0"11";0
if ($n10==0$n3)0echo "TRUE<br>";0
else echo "FALSE<br>";0//0Displays:0boolean TRUE0
if ($n10===0$n3)0echo "TRUE<br>";0
else echo "FALSE<br>";0//0Displays0:0boolean FALSE0
if($n10>0$n2)0echo "TRUE<br>";0
else echo "FALSE<br>";0//0Displays:0boolean TRUE
?>

39
PHP0Basic

PHP data types (Operators):


Comparison Operators

Operator Name Example Description


== Equal $x+==+$y True+if+$x+is+equal+to+$y
=== Identical $x+===+$y True+if+$x+is+equal+to+$y,+and+they+are+of+the+same+type

!= Not+equal $x+!=+$y True+if+$x+is+not+equal+to+$y


<> Not+equal $x+<>+$y True+if+$x+is+not+equal+to+$y
!== Not+identical $x+!==+$y True+if+$x+is+not+equal+to+$y,+or+they+are+not+of+the+same+type

< Less+than $x+<+$y True+if+$x+is+less+than+$y


> Greater+than $x+>+$y True+if+$x+is+greater+than+$y
>= Greater+than+or+equal+to $x+>=+$y True+if+$x+is+greater+than+or+equal+to+$y
<= Less+than+or+equal+to $x+<=+$y True if $x+is less than or equal to+$y
Returns an integer less than,+equal to,+or greater than zero,+
<=> Spaceship $x+<=>+$y
depending on if $x+is less than,+equal to,+or greater than $y 40
PHP0Basic

PHP data types (Operators): <?php


$n10=011;0
$n2=05;0
Incrementing and Decrementing Operators $n30=0$n1++;
• The comparison operators are0used to0 $n40=0++$n2;
ncrement/decrement a0variable's value echo $n3."<br"";0
echo $n4;
?>

Operator Name Description

++$x Pre)increment Increments $x1by one,1then returns $x

$x++ Post)increment Returns1$x,1then1increments1$x1by1one

))$x Pre)decrement Decrements1$x1by1one,1then1returns1$x

$x)) Post)decrement Returns $x,1then decrements $x1by one


41
PHP0Basic

PHP data types (Operators):


Logical0Operators <?php
• The comparison operators are0used to0 $n10=011;0$n20=05;0$n30=0"11";0
compare0two Boolean values if ($n10==0$n30&&0$n1!=$n2)0
echo "TRUE<br>";0
else
echo "FALSE<br>";0//0Displays:0boolean TRUE0
?>

Operator Name Example Description


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
42
PHP0Basic

PHP data types (Operators):

String Operators
• The two operators are0designed for0strings <?php
$str10=0"Hello ";0
$str20=0"my Friends!";0
$str30=0"Class!";0
echo $str10.0$str20.0"<br>";0
$str10.=0$str3;
echo "str3<br>";?>

Operator Name Example Description


. Concatenation $str10.0$str2 Concatenation0of0$str10and0$str2
.= Concatenation0assignment $str10.=0$str2 Appends the $str20to0the $str1

43
PHP0Basic

PHP data types (Operators):

Array Operators
• The comparison operators are0used to0compare0arrays

Operator Name Example Description


+ Union $x)+)$y Union)of)$x)and)$y
== Equality $x)==)$y Returns true if $x)and $y)have the same key/value pairs
Returns true if $x)and $y)have the same key/value pairs in)
=== Identity $x)===)$y
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
!== NonCidentity $x)!==)$y Returns true if $x)is not identical to)$y
44
PHP4Basic

PHP Conditional Statements (if…else):

• Test condi8ons in4the form of expressions that evaluates to4either true or false4and based on
these results you can4perform certain ac8ons
• if statement
• if...else statement
• if...elseif....else statement

<?php
if(condition1){
//"Code to"be executed if condition1"is true
}4elseif(condition2){
//"Code to"be executed if the condition1"is false"and condition2"is true
}4elseif(condition3){
//"Code to"be executed if the condition1"and condition2"are"false"and condition3"is true
}4elseif(condition_n){
//"Code to"be executed if ...
}4else{
//"Code to"be executed if both ALL"conditions before are"false
}?>
45
PHP7Basic

PHP Conditional Statements (Ternary Operator):

• A7shorthand way of writing the if...else statements


• The ternary operator is represented by the question mark (?)7symbol
• It takes7three operands:
• a$condition to$verify
• a$result for$true
• a$result for$false

<?php
if($age7<767){7
echo 'Middle age';7//7output7if age7is less than 67
}7else{7
echo 'Ancient';7//7output7if age7is greater than or equal to767
}
?>

<?php
echo ($age7<718)7?7'Middle age'7:7'Ancient ';
?>
46
PHP5Basic
PHP Conditional Statements (switch):
• The switch statement select one of many blocks of code to5be executed
• The switch>case5statement is an alternative to5the if>elseif>else statement
• Do5"almost"5the same
• The switch>case5statement tests a5variable against a5series5of values until it finds a5match
• Then executes5the block of code corresponding to5that match5...
• ...5And also executes5all the subsequent case5statements till the end of the switch block ...
• ...5The break statement tells PHP5to5break5out5of the switch>case5statement block once it executes5the
code associated with the first true case5automatically
<?php
switch($var){
case5value1:
//5To5be executed if $var=value1
break;
case5value2:
//5To5be executed if $var=value2
break;
...
default:
//5To5be executed if $var5is different from all values
}
?> 47
PHP6Basic
PHP Condi(onal Statements (switch):

<?php
$login6="client";
switch($login){
case6"client":
echo "Hello client.";
//break;
case6"employee":
echo "Hello employee.";
break;
case6"admin":
echo "Hello admin.";
break;
default:
echo "Not known.";
break;
}?>

48
PHP(Basic

PHP Loops:

• The loop is to(automate the repetitive tasks


• As(long as(a(certain condition is met
• Four different types of loops:
• while — loops through a.block of code as.long as.the condition specified evaluates to.true
• do…while — the block of code executed once and then condition is evaluated..If the condition is true the
statement is repeated as.long as.the specified condition is true
• for — loops through a.block of code until the counter reaches a.specified number
• foreach — loops through a.block of code for.each element in.an array

49
PHP/Basic

PHP Loops (while):

• The while statement will loops through a/block of code as/long as/the condition specified in/the
while statement evaluate to/true

<?php
while(condition){ $i/=/0;
///Code to/be executed echo "Even number less then 20:<br>";/
} while($i/</20){/
$i+=2;/
echo $i/./"<br>";/
}
?>/

50
PHP1Basic

PHP Loops (do ... while):

• Loops through a1block of code once


• Repeats the loop as1long as1the specified condition is true
• Always execute1the block of code once
• Check the condition,1and repeat the loop while the specified condition is true
• The condition is tested AFTER executing the statements within the loop

<?php
$i1=10;
echo "Even number less then 20:<br>";1
do{1 <?php
do1{ $i+=2;1 $i1=1100;
//"Code to"be executed;
echo $i1.1"<br>";1 echo "Even number less then 20:<br>";1
}1while (condi/on is true); ]1while($i1<120); do{1
?>1 $i+=2;1
echo $i1.1"<br>";1
]1while($i1<120);
?>1

51
PHP,Basic

PHP Loops (for):

• The for,loop repeats a,block of code as,long as,a,certain condition is met

<?php
echo "Even number less then 20:<br>";,
for,($i=0;,$i,<,20;,$i+=2)
echo $i,.,"<br>";
for(iniJalizaJon;,condiJon;,increment){ ?>,
//,Code to,be executed
}

• initialization — it is used to,initialize the counter variables


• condition — in,the beginning of each iteration,,condition is evaluated.,If it
evaluates to,true,,the loop continues,and the nested statements are,executed
• increment — it updates the loop counter with a,new value.,It is evaluate at
the end of each iteration
52
PHP0Basic

PHP Loops (foreach):


• The foreach loop is used to0iterate over arrays
• loop through each key/value pair in0an array
• For0every loop iteration,0the value of the current array element is assigned to0$value and the
array pointer is moved by one,0until it reaches the last array element

foreach ($array as0$key =>0$value){


//0Code to0be executed <?php
} $person =0array("Albert"=>"Portugal",0
"Jonh"=>"EUA",0"Mary"=>"Tunisia");
foreach ($array as0$value)0{
//0Code to0be executed; foreach($person as0$k0=>0$v)0{
} echo "$0=0$v<br>";
}
?>0

• array — the array over which all its elements are0to0be traversed
• key — the index of the current array element
• value — the content of the current array element

53
PHP0Basic

PHP Loops (foreach):

<?php
$person =0array("Albert"=>"Portugal",0
"Jonh"=>"EUA",0"Mary"=>"Tunisia");

while0(list(,0$value)0=0each0($person))0{0 <?php

echo0"Value:0$value<br>\n";0 $person =0array("Albert"=>"Portugal",0


"Jonh"=>"EUA",0"Mary"=>"Tunisia");
}0
?>0 while0(list($key,0$value)0=0each0($person))0{0
echo0"0Key:0$key;0Value:0$value<br>\n";0
}0
?>0

54
PHP/Basic

PHP Loops (break):

• The break/statement can/be used to/jump out/of a/loop

<?php
for/($n=0;/$n/</20;/$n++)
if ($n/==/10) <?php
break; $person =/array("Albert"=>"Portugal",/
else "Jonh"=>"EUA",/"Mary"=>"Tunisia");
echo $n."<br>";//
?>/ for/($n=0;/$n/<=/2;/$n++)
if ($n/!=/1)
echo $person[$n]."<br>";
else
break;
?>

55
PHP0Basic

PHP Loops (continue):

• The continue0statement breaks0one iteration ...


• ...0And continues0with the next iteration in0the loop

<?php
for0($n=0;0$n0<020;0$n++) <?php
if ($n0%020==00) $person =0array("Albert"=>"Portugal",0
continue; "Jonh"=>"EUA",0"Mary"=>"Tunisia");
else
echo $n."<br>";00 for0($n=0;0$n0<=02;0$n++)
?>0 if ($n0!=01)
echo $person[$n]."<br>";
else
conUnue;
?>

56
PHP/Basic

<?php
PHP Loops (con*nue): for/($x=1;/$x<=10;/$x++)
{
echo "x=$x:<br>";
for/($y=$x;/$y<=10;/$y++)
{
echo "&nbsp;&nbsp y=$y:<br>";
for/($z=$y;/$z<=10;/$z++)
{
<?php if ($z/==/5)
for/($x=1;/$x<=10;/$x++) continue/3;
{ else
echo "x=$x:<br>"; echo "&nbsp;&nbsp;&nbsp;&nbsp;/x=$x,/y=$y,/z=$z<br>";
for/($y=$x;/$y<=10;/$y++) }
{ }
echo "&nbsp;&nbsp y=$y:<br>"; }?>
for/($z=$y;/$z<=10;/$z++)
{
echo "&nbsp;&nbsp;&nbsp;&nbsp;/x=$x,/y=$y,/z=$z<br>";
}
}
}?>

57
PHP+Basic

PHP Func'ons:
• A+function is a+self4contained block of code that performs a+specific task
• PHP+has more+than 1000+built4in+functions
• PHP+allows to+define+own functions
• A+function name must+start with a+letter or underscore character not with a+number,+optionally
followed by the more+letters,+numbers,+or underscore characters.+Function names are+case4
insensitive
• A+function will not execute+automatically when a+page loads
• A+function will be executed by a+call to+the function

<?php
//+Defining the func'on
function functionName($oneParameter,+$twoParameter,+...){ func'on helloworld(){+
//+Code to+be executed echo "Hello World";+
} }+
//+Calling the func'on
helloworld();
?>+

58
PHP2Basic

PHP Functions (Parameters):


• Information can2be passed to2functions through arguments
• An argument is just like a2variable
• The parameters work like placeholder variables within a2function
• They are2replaced at run time2by the values provided to2the function at the time2of invocation
• You can2define2as2many parameters as2you like
• Arguments are2specified after the function name,2inside the parentheses
• For2each parameter a2corresponding argument needs to2be passed to2the function (when it is
called)
<?php
//2Defining the function
function multiplication($p1,2$p2){2
echo $p1."*".$p2."=".$p1*$p2."<br>";2
funcYon funcYonName($oneParameter,2$twoParameter,2...){ }2
//2Code to2be executed //2Calling the function
} multiplication(4,6);
$x2=211;
$y2=23;
multiplication($x,$y);
?>2
59
PHP9Basic

PHP Functions (Optional Parameters and Default Values):

• Func;ons can9have op;onal parameters


• The parameter name,9followed by an equals (=)9sign,9followed by a9default value
• Op;onal parameters have to9be placed at the end

<?php
//9Defining the function
function multiplication($p1,9$p2=7){9
echo $p1."*".$p2."=".$p1*$p2."<br>";9
}9
//9Calling the function
multiplication(4);
$x9=911;
$y9=93;
multiplication($x,$y);
?>9
60
PHP6Basic

PHP Func'ons (Returning Values):

• A6function can6return a6value back to6the script6that called it,6using the return statement
• The return value can6be of any type (including arrays and objects)
• A6function can6not return multiple values,6but can6an array ...

<?php
function multiplication($p1,6$p2){6 <?php
return $p1*$p;6 function multiplication($p1,6$p2){
}6 $sum6=6$p1+$p;
$dif =6$p1T$p;
$x6=611; $mul =6$p1*$p;
$y6=63; return array($sum,$dif,$mul);6
echo multiplication($x,$y); }6
?>6
list($s,$d,$m)6=6multiplication(12,4);
?>6
61
PHP7Basic

PHP Functions (Arguments by Reference):


• There are7two ways you can7pass arguments to7a7func>on:7by value and by reference
• By default,7func>on arguments are7passed by value so that if the value of the argument within
the func>on is changed,7it does7not get affected outside of the func>on
• To7allow a7func>on to7modify its arguments,7they must7be passed by reference
• An argument by reference is done by prepending an ampersand (&)7to7the argument name

<?php
function f7($p1){7
$p17+=77;7 <?php
}7 function f7(&$p1){7
$p17+=77;7
$x7=711; }7
f7($x);
echo $x; $x7=711;
?>7 f7($x);
echo $x;
?>7
62
PHP6Basic

PHP Functions (Variable Scope):

• The scope6of a6variable6determines6which part of the code can6access it


• The locations where the variable can6be accessible determine6the scope6of the variable
• PHP6variables have four types of scopes:
• Local
• Global
• Static
• Function parameters

63
PHP8Basic

PHP Func'ons (Variable Scope4 Local):

• When defining8a8variable8inside a8function,8that variable can8only be accessed within the function


• That the variable is local8to8the function

<?php
function f8(){8
$p8=87;
echo "Inside f():8"8.8$p;8//outputs8Inside f():87
}8

f8();
echo $p;8//outputs8Undefined variable:8p
?>

64
PHP8Basic

PHP Func'ons (Variable Scope4 Global):

• A8variable declared outside of a8function is global


• That you can8accessed anywhere within the script8except inside a8function

<?php
$name =8"Abdel";8

func'on f8(){8
$p8=8123;
echo "Inside f():8p="8.8$p;8//8outputs8p=123
echo "name=".8$name .8"<br>";8//outputs8Undefined variable:8name
}8

f8();
echo "Outside f():8p="8.8$p;8//outputs8Undefined variable:8p
echo "name=".8$name .8"<br>";8//outputs8name=Abdel
?>
65
PHP8Basic

PHP Functions (Variable Scope 4 Global):

• A8variable declared outside of a8function is global


• That you can8accessed anywhere within the script8except inside a8function

<?php
$name =8"Abdel";8 <?php
$msg =8'Portugal';8//8global8var
funcKon f8(){8
$p8=8123; function f()
echo "Inside f():8p="8.8$p;8//8outputs8p=123 {
echo "name=".8$name .8"<br>";8//outputs8Undefined variable:8name $msg =8'Tunisia';8//8local8var
}8 echo "In:8".8$msg ."<br>";8//8outputs8In:Tunisia
}
f8();
echo "Outside f():8p="8.8$p;8//outputs8Undefined variable:8p f();
echo "name=".8$name .8"<br>";8//outputs8name=Abdel echo $msg;8//8outputs8Portugal
?> ?>

66
PHP8Basic

PHP Func'ons (Variable Scope4 Global):

• To8access a8global8variable within a8function use8the global keyword

<?php
$msg =8'Portugal';8//8global8var

function f()
{
global8$msg;8//8global8var
echo "In:8".8$msg ."<br>";8//8outputs8In:Portugal
$msg =8'Tunisia';
}

echo $msg ."<br>";8//8outputs8Portugal


f();
echo $msg ."<br>";8//8outputs8Tunisia
?>

67
PHP8Basic

PHP Func'ons (Variable Scope4 Sta'c):

• A8static variable retains its value between function calls


• A8static variable is only accessible inside the function
• To8define8a8static variable,8you use8the static keyword

<?php

func'on f()
{
sta'c $p=1;8
echo $p8."<br>";8//8outputs818283
$p++;
}

f();
f();
f();
?>
68
PHP(Basic

Quiz:

Creating a(variable in(PHP:


o can(start with the character '$'
o always ends with the character '$'(
o always starts with the character '$'
o None of the above

The PHP(language is:(or or o(Bootstrap framework o


o compiled
o interconnected
o Bootstrap framework
o None of the above

69
PHP(Basic

Quiz:

Considering the PHP(language,(if the code contains the variables "$color",("$COLOR",(and "$coLOR",(will result:(
o which are(interpreted as(the same variable
o which are(interpreted as(3(different variables
o in(a(syntax error(message
o in(a(semantic error(message

The PHP(language supports the following data(types:(


o String,(Integer,(Float/Double,(Boolean,(Array,(Object,(NULL,(Resource
o String,(Integer,(Float/Double,(Boolean,(Array
o String,(Integer,(Boolean,(Array
o String,(Integer,(Float/Double,(Boolean

70
PHP(Basic

Quiz:

In(PHP,(what is the operator used to(check if two variables are(equal and of the same data(type?
o !=
o =
o ==
o ===

The JSP(language has the following control structures:


! if
! array
! for(
! session

71
PHP(Basic

Quiz:

The PHP(programming language allows a(function to(have parameters by:


! return
! null
! reference
! value

From the following options,(indicate the valid options for(referencing an element of an array:
! $a[1,"cor"]
! $a[1][3](
! f $a[1]["color"]
! $a(1)("color")

72
PHP(Basic

Quiz:

Write the func4on with the name “f_quiz”,(in(PHP,(that simultaneously returns half,(double and the square of the
value passed in(the parameter,(named “param1”,(as(a(reference.

73

You might also like