SlideShare a Scribd company logo
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Introduction to PHP (Hypertext Preprocessor)
PHP Tags:
When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop
interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different
documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the
text through echo or print.
<?php if ($expression == true){ ?>
This will show if the expression is true.
<?php } else { ?>
Otherwise this will show.
<?php } ?>
PHP Comments:
<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
PHP Datatypes:
Boolean (TRUE/FALSE) – case insensitive
False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables)
True – Every other value including NAN
Integer
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
0 = False, Null
1 = True
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Floating Point Numbers
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Strings (Single quoted/ Double quoted)
<?php
echo 'this is a simple string';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I'll be back"';
// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';
// Outputs: This will not expand: n a newline
echo 'This will not expand: n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
<?php
$juice = "apple";
echo "He drank some $juice juice.";
?>
<?php
$str = 'abc';
var_dump($str[1]);
var_dump(isset($str[1]));
?>
. (DOT) – to concat strings
“1” – True
“” – False/ Null
Array
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
$array1 = array("foo", "bar", "hello", "world");
var_dump($array1);
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
<?php
$arr = array(5 => 1, 12 => 2);
$arr[13] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
PHP Variables:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-
sensitive.
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Predefined Variables:
$GLOBALS – References all variables available in global scope
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "n";
echo '$foo in current scope: ' . $foo . "n";
}
$foo = "Example content";
test();
?>
$_SERVER – server and execution environment information
<?php
$indicesServer = array(
'PHP_SELF',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'REQUEST_TIME',
'QUERY_STRING',
'DOCUMENT_ROOT',
'HTTPS',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REMOTE_USER',
'SERVER_PORT',
'SCRIPT_NAME',
'REQUEST_URI') ;
echo '<table style=”width:100%;”>' ;
foreach ($indicesServer as $arg) {
if (isset($_SERVER[$arg])) {
echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ;
}
else {
echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ;
}
}
echo '</table>' ;
?>
$_GET – an associative array of variables passed to the current script via the URL parameters
$_POST – an associative array of variables passed to the current script via the HTTP POST method when using
application/x-www-form-urlencoded or, multipart/form-data as the HTTP
$_FILES – an associative array of items uploaded to the current script via the HTTP POST method
$_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_SESSION -- An associative array containing session variables available to the current script.
$_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Operators and Operator Precedence:
visit here  https://www.php.net/manual/en/language.operators.php
Control Structures:
if-elseif-else statement
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
while loop
<?php
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
?>
do-while loop
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
for loop
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
foreach loop
<?php
$a = array(1, 2, 3, 17);
$i = 0;
foreach ($a as $v) {
echo "$a[$i] => $v.n";
$i++;
}
$a = array(
"one" => 1,
"two" => 2,
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "$a[$k] => $v.n";
}
//multi-dimensional array
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2n";
}
}
?>
break, continue, switch, return
similar as before
include/require
The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it
cannot find a file; this is different behavior from require, which will emit a fatal error.
within vars.php file
<?php
$color = 'green';
$fruit = 'apple';
?>
within test.php file
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
include_once / require_once
The include_once statement includes and evaluates the specified file during the execution of the script. This is a
behavior similar to the include statement, with the only difference being that if the code from a file has already been
included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included
just once.
<?php
var_dump(include_once 'fakefile.ext'); // bool(false)
var_dump(include_once 'fakefile.ext'); // bool(true)
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Functions:
<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.n";
}
?>
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
?>
///anonymous functions in PHP
<?php
$greet = function($name)
{
printf("Hello %srn", $name);
};
$greet('World');
$greet('PHP');
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Some Functions:
Variable Handling
Functions
empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE.
isset($var) -- Determine if a variable is declared and value is different than NULL
unset($var) -- Unset a given variable or, destroys a variable
print_r ($var) -- Prints human-readable information about a variable
var_dump($var) -- Dumps information about a variable
Array Functions count($a) -- Count all elements in an array
array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array
array_keys($array) -- Return all the keys of an array
array_values($array) -- Return all the values of an array
array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array
array_pop($stack) -- Pop the element off the end of array
array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning
of an array
array_shift($stack) -- Shift an element off the beginning of array
array_search('green', $array) -- Searches the array for a given value and returns the first
corresponding key if successful
array_slice($input, 0, 3) -- Extract a slice of the array
array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and
replace it with something else
sort($array), rsort($array), ksort($array), krsort($array)
String Functions strlen(‘abcd’) -- Get string length
echo "Hello World" -- Output one or more strings
explode(" ", $pizza) -- split a string by a string
implode(",", $array) -- Join array elements with a string
htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities
html_entity_decode(“I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt”) -- Convert HTML
entities to their corresponding characters
htmlspecialchars($str) — Convert special characters to HTML entities
htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters
md5($password) – calculate the md5 hashing of user string
sha1($password) – calculate the sha1 hashing of user string
parse_str($str,$output_array) -- Parses the string into variables
example:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
// Recommended
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

More Related Content

What's hot (17)

PDF
jQuery Essentials
Marc Grabanski
 
PDF
Neat tricks to bypass CSRF-protection
Mikhail Egorov
 
PPT
Arrays in PHP
Compare Infobase Limited
 
PPTX
PHP-MySQL Database Connectivity Using XAMPP Server
Rajiv Bhatia
 
DOCX
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
PDF
java 8 람다식 소개와 의미 고찰
Sungchul Park
 
PPTX
Owasp Top 10 A1: Injection
Michael Hendrickx
 
PDF
Pairwise testing - Strategic test case design
XBOSoft
 
PPTX
PHPUnit: from zero to hero
Jeremy Cook
 
PDF
The JavaScript Programming Language
guestceb98b
 
PPTX
Jsp
Pooja Verma
 
PPTX
Php cookies
JIGAR MAKHIJA
 
PDF
SymfonyLive Online 2023 - Is SOLID dead? .pdf
Łukasz Chruściel
 
PPTX
Threat Hunting Web Shells Using Splunk
jamesmbower
 
KEY
HTML5 Form Validation
Ian Oxley
 
PPTX
OSINT for Proactive Defense - RootConf 2019
RedHunt Labs
 
jQuery Essentials
Marc Grabanski
 
Neat tricks to bypass CSRF-protection
Mikhail Egorov
 
PHP-MySQL Database Connectivity Using XAMPP Server
Rajiv Bhatia
 
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
java 8 람다식 소개와 의미 고찰
Sungchul Park
 
Owasp Top 10 A1: Injection
Michael Hendrickx
 
Pairwise testing - Strategic test case design
XBOSoft
 
PHPUnit: from zero to hero
Jeremy Cook
 
The JavaScript Programming Language
guestceb98b
 
Php cookies
JIGAR MAKHIJA
 
SymfonyLive Online 2023 - Is SOLID dead? .pdf
Łukasz Chruściel
 
Threat Hunting Web Shells Using Splunk
jamesmbower
 
HTML5 Form Validation
Ian Oxley
 
OSINT for Proactive Defense - RootConf 2019
RedHunt Labs
 

Similar to Web 8 | Introduction to PHP (20)

PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
PPT
Php mysql
Alebachew Zewdu
 
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
PPT
slidesharenew1
truptitasol
 
PPT
My cool new Slideshow!
omprakash_bagrao_prdxn
 
PPT
PHP
sometech
 
PPTX
Php1
Shamik Tiwari
 
PPTX
Ch1(introduction to php)
Chhom Karath
 
PPTX
Introduction in php part 2
Bozhidar Boshnakov
 
PPTX
Day1
IRWAA LLC
 
PDF
Php Crash Course - Macq Electronique 2010
Michelangelo van Dam
 
PPT
Php mysql
Ajit Yadav
 
PPTX
unit 1.pptx
adityathote3
 
PPT
Php course-in-navimumbai
vibrantuser
 
PDF
Introduction to PHP
Bradley Holt
 
PPTX
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
PDF
Introduction to php
KIRAN KUMAR SILIVERI
 
PDF
2014 database - course 2 - php
Hung-yu Lin
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Php mysql
Alebachew Zewdu
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
slidesharenew1
truptitasol
 
My cool new Slideshow!
omprakash_bagrao_prdxn
 
Ch1(introduction to php)
Chhom Karath
 
Introduction in php part 2
Bozhidar Boshnakov
 
Day1
IRWAA LLC
 
Php Crash Course - Macq Electronique 2010
Michelangelo van Dam
 
Php mysql
Ajit Yadav
 
unit 1.pptx
adityathote3
 
Php course-in-navimumbai
vibrantuser
 
Introduction to PHP
Bradley Holt
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
Introduction to php
KIRAN KUMAR SILIVERI
 
2014 database - course 2 - php
Hung-yu Lin
 
Ad

More from Mohammad Imam Hossain (20)

PDF
DS & Algo 6 - Offline Assignment 6
Mohammad Imam Hossain
 
PDF
DS & Algo 6 - Dynamic Programming
Mohammad Imam Hossain
 
PDF
DS & Algo 5 - Disjoint Set and MST
Mohammad Imam Hossain
 
PDF
DS & Algo 4 - Graph and Shortest Path Search
Mohammad Imam Hossain
 
PDF
DS & Algo 3 - Offline Assignment 3
Mohammad Imam Hossain
 
PDF
DS & Algo 3 - Divide and Conquer
Mohammad Imam Hossain
 
PDF
DS & Algo 2 - Offline Assignment 2
Mohammad Imam Hossain
 
PDF
DS & Algo 2 - Recursion
Mohammad Imam Hossain
 
PDF
DS & Algo 1 - Offline Assignment 1
Mohammad Imam Hossain
 
PDF
DS & Algo 1 - C++ and STL Introduction
Mohammad Imam Hossain
 
PDF
DBMS 1 | Introduction to DBMS
Mohammad Imam Hossain
 
PDF
DBMS 10 | Database Transactions
Mohammad Imam Hossain
 
PDF
DBMS 3 | ER Diagram to Relational Schema
Mohammad Imam Hossain
 
PDF
DBMS 2 | Entity Relationship Model
Mohammad Imam Hossain
 
PDF
DBMS 7 | Relational Query Language
Mohammad Imam Hossain
 
PDF
DBMS 4 | MySQL - DDL & DML Commands
Mohammad Imam Hossain
 
PDF
DBMS 5 | MySQL Practice List - HR Schema
Mohammad Imam Hossain
 
PDF
TOC 10 | Turing Machine
Mohammad Imam Hossain
 
PDF
TOC 9 | Pushdown Automata
Mohammad Imam Hossain
 
PDF
TOC 8 | Derivation, Parse Tree & Ambiguity Check
Mohammad Imam Hossain
 
DS & Algo 6 - Offline Assignment 6
Mohammad Imam Hossain
 
DS & Algo 6 - Dynamic Programming
Mohammad Imam Hossain
 
DS & Algo 5 - Disjoint Set and MST
Mohammad Imam Hossain
 
DS & Algo 4 - Graph and Shortest Path Search
Mohammad Imam Hossain
 
DS & Algo 3 - Offline Assignment 3
Mohammad Imam Hossain
 
DS & Algo 3 - Divide and Conquer
Mohammad Imam Hossain
 
DS & Algo 2 - Offline Assignment 2
Mohammad Imam Hossain
 
DS & Algo 2 - Recursion
Mohammad Imam Hossain
 
DS & Algo 1 - Offline Assignment 1
Mohammad Imam Hossain
 
DS & Algo 1 - C++ and STL Introduction
Mohammad Imam Hossain
 
DBMS 1 | Introduction to DBMS
Mohammad Imam Hossain
 
DBMS 10 | Database Transactions
Mohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
Mohammad Imam Hossain
 
DBMS 2 | Entity Relationship Model
Mohammad Imam Hossain
 
DBMS 7 | Relational Query Language
Mohammad Imam Hossain
 
DBMS 4 | MySQL - DDL & DML Commands
Mohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
Mohammad Imam Hossain
 
TOC 10 | Turing Machine
Mohammad Imam Hossain
 
TOC 9 | Pushdown Automata
Mohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
Mohammad Imam Hossain
 
Ad

Recently uploaded (20)

PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PDF
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PPTX
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
PPTX
How Physics Enhances Our Quality of Life.pptx
AngeliqueTolentinoDe
 
PDF
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
PPT
21st Century Literature from the Philippines and the World QUARTER 1/ MODULE ...
isaacmendoza76
 
PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
PPTX
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PDF
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PPTX
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
PDF
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
PDF
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PPTX
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
week 1-2.pptx yueojerjdeiwmwjsweuwikwswiewjrwiwkw
rebznelz
 
How Physics Enhances Our Quality of Life.pptx
AngeliqueTolentinoDe
 
Wikinomics How Mass Collaboration Changes Everything Don Tapscott
wcsqyzf5909
 
21st Century Literature from the Philippines and the World QUARTER 1/ MODULE ...
isaacmendoza76
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
Practice Gardens and Polytechnic Education: Utilizing Nature in 1950s’ Hu...
Lajos Somogyvári
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
Comparing Translational and Rotational Motion.pptx
AngeliqueTolentinoDe
 
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
How to Create & Manage Stages in Odoo 18 Helpdesk
Celine George
 

Web 8 | Introduction to PHP

  • 1. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] Introduction to PHP (Hypertext Preprocessor) PHP Tags: When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. <p>This is going to be ignored by PHP and displayed by the browser.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored by PHP and displayed by the browser.</p> For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print. <?php if ($expression == true){ ?> This will show if the expression is true. <?php } else { ?> Otherwise this will show. <?php } ?> PHP Comments: <?php echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */ echo 'This is yet another test'; echo 'One Final Test'; # This is a one-line shell-style comment ?> PHP Datatypes: Boolean (TRUE/FALSE) – case insensitive False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables) True – Every other value including NAN Integer <?php $a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) $a = 0b11111111; // binary number (equivalent to 255 decimal) ?> 0 = False, Null 1 = True
  • 2. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] Floating Point Numbers <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?> Strings (Single quoted/ Double quoted) <?php echo 'this is a simple string'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I'll be back"'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // Outputs: This will not expand: n a newline echo 'This will not expand: n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> <?php $juice = "apple"; echo "He drank some $juice juice."; ?> <?php $str = 'abc'; var_dump($str[1]); var_dump(isset($str[1])); ?> . (DOT) – to concat strings “1” – True “” – False/ Null Array <?php $array = array( "foo" => "bar", "bar" => "foo", ); $array1 = array("foo", "bar", "hello", "world"); var_dump($array1); ?>
  • 3. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] <?php $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?> <?php $arr = array(5 => 1, 12 => 2); $arr[13] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> PHP Variables: Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case- sensitive. <?php $a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); ?> <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?>
  • 4. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] Predefined Variables: $GLOBALS – References all variables available in global scope <?php function test() { $foo = "local variable"; echo '$foo in global scope: ' . $GLOBALS["foo"] . "n"; echo '$foo in current scope: ' . $foo . "n"; } $foo = "Example content"; test(); ?> $_SERVER – server and execution environment information <?php $indicesServer = array( 'PHP_SELF', 'SERVER_ADDR', 'SERVER_NAME', 'SERVER_PROTOCOL', 'REQUEST_METHOD', 'REQUEST_TIME', 'QUERY_STRING', 'DOCUMENT_ROOT', 'HTTPS', 'REMOTE_ADDR', 'REMOTE_HOST', 'REMOTE_PORT', 'REMOTE_USER', 'SERVER_PORT', 'SCRIPT_NAME', 'REQUEST_URI') ; echo '<table style=”width:100%;”>' ; foreach ($indicesServer as $arg) { if (isset($_SERVER[$arg])) { echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ; } else { echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ; } } echo '</table>' ; ?> $_GET – an associative array of variables passed to the current script via the URL parameters $_POST – an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or, multipart/form-data as the HTTP $_FILES – an associative array of items uploaded to the current script via the HTTP POST method $_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. $_SESSION -- An associative array containing session variables available to the current script. $_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
  • 5. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] Operators and Operator Precedence: visit here  https://www.php.net/manual/en/language.operators.php Control Structures: if-elseif-else statement <?php if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> while loop <?php $i = 1; while ($i <= 10) { echo $i++; /* the printed value would be $i before the increment (post-increment) */ } ?> do-while loop <?php $i = 0; do { echo $i; } while ($i > 0); ?> for loop <?php for ($i = 1; $i <= 10; $i++) { echo $i; } ?> foreach loop <?php $a = array(1, 2, 3, 17); $i = 0; foreach ($a as $v) { echo "$a[$i] => $v.n"; $i++; } $a = array( "one" => 1, "two" => 2,
  • 6. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "$a[$k] => $v.n"; } //multi-dimensional array $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2n"; } } ?> break, continue, switch, return similar as before include/require The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error. within vars.php file <?php $color = 'green'; $fruit = 'apple'; ?> within test.php file <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?> include_once / require_once The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once. <?php var_dump(include_once 'fakefile.ext'); // bool(false) var_dump(include_once 'fakefile.ext'); // bool(true) ?>
  • 7. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] Functions: <?php $makefoo = true; /* We can't call foo() from here since it doesn't exist yet, but we can call bar() */ bar(); if ($makefoo) { function foo() { echo "I don't exist until program execution reaches me.n"; } } /* Now we can safely call foo() since $makefoo evaluated to true */ if ($makefoo) foo(); function bar() { echo "I exist immediately upon program start.n"; } ?> <?php function foo() { function bar() { echo "I don't exist until foo() is called.n"; } } /* We can't call bar() yet since it doesn't exist. */ foo(); /* Now we can call bar(), foo()'s processing has made it accessible. */ bar(); ?> ///anonymous functions in PHP <?php $greet = function($name) { printf("Hello %srn", $name); }; $greet('World'); $greet('PHP'); ?>
  • 8. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: [email protected] Some Functions: Variable Handling Functions empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE. isset($var) -- Determine if a variable is declared and value is different than NULL unset($var) -- Unset a given variable or, destroys a variable print_r ($var) -- Prints human-readable information about a variable var_dump($var) -- Dumps information about a variable Array Functions count($a) -- Count all elements in an array array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array array_keys($array) -- Return all the keys of an array array_values($array) -- Return all the values of an array array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array array_pop($stack) -- Pop the element off the end of array array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning of an array array_shift($stack) -- Shift an element off the beginning of array array_search('green', $array) -- Searches the array for a given value and returns the first corresponding key if successful array_slice($input, 0, 3) -- Extract a slice of the array array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and replace it with something else sort($array), rsort($array), ksort($array), krsort($array) String Functions strlen(‘abcd’) -- Get string length echo "Hello World" -- Output one or more strings explode(" ", $pizza) -- split a string by a string implode(",", $array) -- Join array elements with a string htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities html_entity_decode(“I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt”) -- Convert HTML entities to their corresponding characters htmlspecialchars($str) — Convert special characters to HTML entities htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters md5($password) – calculate the md5 hashing of user string sha1($password) – calculate the sha1 hashing of user string parse_str($str,$output_array) -- Parses the string into variables example: $str = "first=value&arr[]=foo+bar&arr[]=baz"; // Recommended parse_str($str, $output); echo $output['first']; // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz