SlideShare ist ein Scribd-Unternehmen logo
1 von 76
Course overview unit wise
Unit-I: Discussion about PHP Concepts
Unit-II: Covers XML Concepts
Unit-III: Covers Servlets Concepts
Unit-IV: Covers JSP(Java Server Page) Concepts
Unit-V: Covers Java Script Concepts
Unit-I: Discussion about PHP Concepts
Introduction to PHP: Declaring variables, data types,
arrays, strings, operators, expressions, control structures,
functions, reading data from web form controls like text
boxes, radio buttons, lists etc,. Handling File uploads,
connecting to database (MYSQL as reference), executing
simple queries, handling results, handling sessions and
cookies.
File Handling in PHP: File operations like opening, closing,
reading, writing, appending, deleting etc., on text and
binary files listing directories.
Unit-II: Discussion about XML Concepts
XML : Introduction to XML, Defining XML tags,
their attributes and values, Document type
definition, XML Schemas, Document Object
model, Presenting XHTML,
Parsing XML Data: DOM and SAX Parsers in Java
Unit-III: Discussion about Servlets Concepts
Introduction to servlets: Common Gateway
Interface (CGI), Lifecycle of a Serverlet, Deploying
a servlet, The Servlet API, The javax.servlet
Package, Reading Servelet parameters, Reading
Initialization parameters. The javax.servlet HTTP
package, Handling Http Request & Responses,
Using Cookies-Session Tracking, SecurityIssues.
Connecting to database using JDBC
Unit-IV: Discussion about JSP Concepts
Introduction to JSP: The Anatomy of a JSP Page,
JSP Processing, Declarations, Directives,
Expressions, Code Snippets,, Implicit objects,
Using Beans in JSP Pages, Using Cookies and
Session for session tracking, Connecting to
Database in JSP.
Unit-V: Discussion about Java Scripts Concepts
Client side scripting: Introduction to Java Script,
declaring variables, scope of variables, functions,
event handlers(onclick, onsubmit, etc.,)
,Document Object model, Form validation.
Referece Books
T1- Web Technologies, Uttam K Roy, Oxford University Press
T2- The complete reference PHP- Steven Holzner, Tata McGraw- Hill
T3-Web Programming, building internet applications, Chris Bates 2nd edition.
T4- The Complete Reference java2 fifth edition by Patrik Naughton and
Herbert Schild, TMH.
T5- Java Server Pages- Hans Bergsten, SPD O’Reilly.
WEB REFERENCES
http://www.coreservlets.com.
http://www.serverside.com.
http://www.roseindia.net/java/
http://www.roseindia.net/servlets/
http://www.w3schools.com
UNIT-I
Introduction to PHP:( part 1)
 Declaring variables
 Data types
 Arrays
 Strings
 Operators
 Expressions
 Control structures
 Functions
Introduction to PHP: (part2)
 Reading data from web form controls like text
boxes, radio buttons, lists etc,.
 Handling File uploads
 Connecting to database (MYSQL as reference),
executing simple queries, handling results,
handling sessions and cookies.
 File Handling in PHP: File operations like
opening, closing, reading, writing, appending,
deleting etc., on text and binary files listing
directories.
UNIT-I
Introduction to PHP:
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source server side
scripting language
PHP scripts are executed on the server
PHP is free to download and use
Introduction to 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
Introduction to PHP: Why PHP?
PHP runs on various platforms (Windows, Linux, Unix,
Mac OS X, etc.)
PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is easy to learn and runs efficiently on the server
side
PHP Installation
To start using PHP, you can:
Find a web host with PHP and MySQL support
Install a web server on your own PC, and then install
PHP and MySQL
The official PHP website (PHP.net) has installation
instructions for
PHP: http://php.net/manual/en/install.php
PHP Syntax:
A PHP script is executed on the server, and the plain
HTML result is sent back to the browser.
Basic PHP Syntax
<?php
// PHP code goes here
?>
PHP Syntax:
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP
scripting code.
An example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text
"Hello World!" on a web page:
Example PHP code:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Output:
My first PHP page
Hello World
Comments in PHP code:
PHP supports Single line and Multiline Comments
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
Case Sensitivity in PHP code:
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Case Sensitivity in PHP code:
However, In PHP, variable names are case-sensitive.
In the example below, all three variable names are not equal:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
Output:
My car is red
My house is
My boat is
PHP Variables:
Variables are "containers“ for storing information.
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
</body>
</html>
PHP Variables:
After the execution of the statements above,
the variable $txt will hold the value Hello world!,
the variable $x will hold the value 5, and
the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the
value.
Note: Unlike other programming languages, PHP has no command for
declaring a variable. It is created the moment you first assign a value to it.
PHP Variables:
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Rules for 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 (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
PHP Variables:
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example1
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
Example 2
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example 3
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
PHP ”echo” and “print” Statements:
In PHP there are two basic ways to get output: echo
and print.
echo and print are more or less the same.
They are both used to output data to the screen.
The differences are small:
echo has no return value while print has a return value of 1 so it can be
used in expressions.
echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
PHP ”echo” and “print” Statements:
The PHP echo Statement
The echo statement can be used with or without parentheses:
echo or echo().
Display Text Display variable
Example1
<?php
echo "This ", "string ", "was
", "made ", "with multiple
parameters.";
echo "<h2>PHP is Fun!</h2>";
?>
Example 2
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
The PHP print Statement:
The print statement can be used with or without parentheses:
print or print().
Display Text Display variable
Example1
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Example 2
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
PHP Data Types
PHP has a total of eight data types which we use to construct our
variables −
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string
operations.'
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can
package up both other kinds of values and functions that are specific
to the class.
Resources − are special variables that hold references to resources
external to PHP (such as database connections).
PHP Data Types (Integers)
Integers − are whole numbers, without a decimal point, like 4195.
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 three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based -
prefixed with 0)
PHP Data Types (Integers)
Example:int Example: float
Output: int(5985) output: float(10.5985)
The PHP var_dump() function returns the data type and value
<?php
$x = 5985;
var_dump($x);
?>
<?php
$x = 10.5985;
var_dump($x);
?>
PHP Data Types (NULL)
Null is a special data type which can have only one value:
NULL.
A variable of data type NULL is a variable that has no value
assigned to it.
Tip: If a variable is created without a value, it is automatically
assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example:NULL
The PHP var_dump() function returns the data type and value
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
output: NULL
PHP Data Types (Arrays)
An array stores multiple values in one single variable.
Example: Array
Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Data Types (Arrays)
An array stores multiple values in one single variable.
Example: Array
Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Data Types (Objects)
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 Data Types (Objects) Example:
<?php
class Car
{
function Car()
{
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model;
?> Output: VW
PHP Arrays
An array is a data structure that stores one or more similar type of
values under a single name.
And you can access the values by referring to an index number.
For example:
if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
PHP Arrays
Create an Array in PHP
In PHP, the array() function is used to create
an array:
array();
PHP Arrays
In PHP, 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
PHP Arrays (Indexed arrays)
There are two ways to create indexed arrays:
•The index can be assigned automatically (index always
starts at 0),
like this: $cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
PHP Arrays(Indexed Arrays)
The following example creates an indexed array named $cars,
assigns three elements to it, and then prints a text containing the
array values:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output:
I like Volvo, BMW and Toyota.
PHP Arrays(Indexed Arrays)
Get The Length of an Array –
The count() function is used to return the length
(the number of elements) of an array:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
PHP Arrays(Indexed Arrays)
Loop Through an Indexed Array
To loop through and print all the values of an indexed
array, you could use a for loop, like this:
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Arrays(Associative Arrays)
The associative arrays are very similar to numeric arrays in term
of functionality but they are different in terms of their index.
Associative array will have their index as string so that you can
establish a strong association between key and values.
Example:
To store the salaries of employees in an array, we could use the
employees names as the keys in our associative array, and the
value would be their respective salary.
PHP Arrays(Associative Arrays)
Example:
<html>
<body>
<?php /* First method to create associate array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body>
</html>
PHP Arrays(Multidimensional Arrays)
A multi-dimensional 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.
Values in the multi-dimensional array are accessed using
multiple index.
Example
In this example we create a two dimensional array to store marks
of three students in three subjects −
PHP Arrays(Multidimensional Arrays)
Example:
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
PHP Strings
Def: A string is a sequence of characters, like "Hello world!".
Example: Following are valid strings
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = “ "; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences
PHP Strings
Example
<?php
$variable = "name";
$literally = 'My $variable will not print!n';
print($literally);
print "<br />";
$literally = "My $variable will print!n";
print($literally);
?>
Output:
My $variable will not print!n
My name will print!n
PHP Strings Functions
The PHP strlen() function returns the length of a string.
The PHP strrev() function reverses a string:
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If
no match is found, it will return FALSE.
The PHP str_replace() function replaces some characters with some other characters
in a string.
strcmp() Compares two strings (case-sensitive)
strcasecmp() Compares two strings (case-insensitive)
str_word_count() Count the number of words in a string
strncmp() String comparison of the first n characters (case-sensitive)..etc.
PHP String Functions Examples
<?php
echo strlen("Hello world!");
?>
// outputs 12
<?php
echo str_word_count("Hello world!");
?>
// outputs 2
<?php
echo strrev("Hello world!");
?>
// outputs !dlrow olleH
<?php
echo strpos("Hello world!", "world");
?>
// outputs 6
PHP Operators
Operators are used to perform operations on variables and
values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
PHP Operators(Arithmetic operators)
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 (Introduced in PHP 5.6)
PHP Operators(Assignment operators)
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
PHP Operators(Comparison operators)
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
PHP Operators(Increment/Decrement operators)
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Operators(Logical operators)
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Operator Name 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
PHP Operators(String operators)
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 Operators(String operators)
Ex1: Ex2:<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
echo $txt1 . $txt2;
?>
</body>
</html>
Output: Hello world!
<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
</body>
</html>
Output: Hello world!
PHP Operators(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
PHP Operators(Array operators)
Ex1: + operator Ex2: === operator
<!DOCTYPE html>
<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
print_r($x + $y); // union of $x and $y
?>
</body>
</html>
Output:
Array ( [a] => red [b] => green [c] => blue
[d] => yellow )
<!DOCTYPE html>
<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
var_dump($x === $y);
?>
</body>
</html>
Output: bool(false)
PHP Control Structures
PHP Control Structures are categorized into two types:
Conditional Statements
Looping Statements
PHP Control Structures(Conditional Statements)
Conditional statements are used to perform different
actions based on different conditions.
In PHP we have the following conditional statements:
if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and
another code if that condition is false
if...elseif....else statement - executes different codes for more
than two conditions
switch statement - selects one of many blocks of code to be
executed
PHP Control Structures(Conditional Statements)
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than
20:
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP Control Structures(Conditional Statements)
PHP - The if...else Statement
The if....else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
PHP Control Structures(Conditional Statements)
PHP - The if...else Statement
The example below will output "Have a good day!" if the current time is less than 20, and
"Have a good night!" otherwise:
Example:
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
PHP Control Structures(Conditional Statements)
PHP - The if...elseif....else Statement
The if....elseif...else statement executes different codes for more than two conditions.
Syntax:
if (condition)
{
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
PHP Control Structures(Conditional Statements)
PHP - The if...elseif....else Statement
Example:
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
}
elseif ($t < "20")
{
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>
PHP Control Structures(Conditional Statements)
The switch statement is used to perform different actions based on different conditions.
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
PHP Control Structures(Conditional Statements)
Example:
<?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!";
}
?>
PHP Control Structures(Looping Statements)
PHP while loops execute a block of code while the specified
condition is true.
PHP Loops:
In PHP, we have the following looping statements:
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
PHP Control Structures(Looping Statements)
The PHP while Loop
The while loop executes a block of code as long as the specified
condition is true.
Syntax: Ex:
while (condition is true)
{
code to be executed;
}
<?php
$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>
PHP Control Structures(Looping Statements)
The PHP do…while Loop
The while loop executes a block of code as long as the specified
condition is true.
Syntax: Ex:
do
{
code to be executed;
} while (condition is true) ;
<?php
$x = 1;
do
{
echo "The number is: $x <br>";
$x++;
} while($x <= 5) ;
?>
PHP Control Structures(Looping Statements)
PHP for loops execute a block of code a specified number of times.
The PHP for Loop
The for loop is used when you know in advance how many times the script should
run.
Syntax:
for (init counter; test counter; increment counter)
{
code to be executed;
}
Parameters:
init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value
PHP Control Structures(Looping Statements)
PHP for loops execute a block of code a specified number of times.
The PHP for Loop
Example: Output:
<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>
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
PHP Control Structures(Looping Statements)
The PHP foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value and
the array pointer is moved by one, until it reaches the last array element.
PHP Control Structures(Looping Statements)
The PHP foreach Loop
Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>

Weitere ähnliche Inhalte

Was ist angesagt?

Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architecture
Iblesoft
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 

Was ist angesagt? (20)

PHP slides
PHP slidesPHP slides
PHP slides
 
php
phpphp
php
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Json
JsonJson
Json
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architecture
 
Php array
Php arrayPhp array
Php array
 
Php
PhpPhp
Php
 
Html forms
Html formsHtml forms
Html forms
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
PHP
 PHP PHP
PHP
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in php
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 

Ähnlich wie Php Unit 1

PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
Swanand Pol
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 

Ähnlich wie Php Unit 1 (20)

PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Introduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHPIntroduction to PHP - Basics of PHP
Introduction to PHP - Basics of PHP
 
Php by shivitomer
Php by shivitomerPhp by shivitomer
Php by shivitomer
 
PHP Training Part1
PHP Training Part1PHP Training Part1
PHP Training Part1
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP Comprehensive Overview
PHP Comprehensive OverviewPHP Comprehensive Overview
PHP Comprehensive Overview
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 
phptutorial
phptutorialphptutorial
phptutorial
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php a dynamic web scripting language
Php   a dynamic web scripting languagePhp   a dynamic web scripting language
Php a dynamic web scripting language
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Mdst 3559-02-15-php
Mdst 3559-02-15-phpMdst 3559-02-15-php
Mdst 3559-02-15-php
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Kürzlich hochgeladen (20)

SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

Php Unit 1

  • 1.
  • 2. Course overview unit wise Unit-I: Discussion about PHP Concepts Unit-II: Covers XML Concepts Unit-III: Covers Servlets Concepts Unit-IV: Covers JSP(Java Server Page) Concepts Unit-V: Covers Java Script Concepts
  • 3. Unit-I: Discussion about PHP Concepts Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions, control structures, functions, reading data from web form controls like text boxes, radio buttons, lists etc,. Handling File uploads, connecting to database (MYSQL as reference), executing simple queries, handling results, handling sessions and cookies. File Handling in PHP: File operations like opening, closing, reading, writing, appending, deleting etc., on text and binary files listing directories.
  • 4. Unit-II: Discussion about XML Concepts XML : Introduction to XML, Defining XML tags, their attributes and values, Document type definition, XML Schemas, Document Object model, Presenting XHTML, Parsing XML Data: DOM and SAX Parsers in Java
  • 5. Unit-III: Discussion about Servlets Concepts Introduction to servlets: Common Gateway Interface (CGI), Lifecycle of a Serverlet, Deploying a servlet, The Servlet API, The javax.servlet Package, Reading Servelet parameters, Reading Initialization parameters. The javax.servlet HTTP package, Handling Http Request & Responses, Using Cookies-Session Tracking, SecurityIssues. Connecting to database using JDBC
  • 6. Unit-IV: Discussion about JSP Concepts Introduction to JSP: The Anatomy of a JSP Page, JSP Processing, Declarations, Directives, Expressions, Code Snippets,, Implicit objects, Using Beans in JSP Pages, Using Cookies and Session for session tracking, Connecting to Database in JSP.
  • 7. Unit-V: Discussion about Java Scripts Concepts Client side scripting: Introduction to Java Script, declaring variables, scope of variables, functions, event handlers(onclick, onsubmit, etc.,) ,Document Object model, Form validation.
  • 8. Referece Books T1- Web Technologies, Uttam K Roy, Oxford University Press T2- The complete reference PHP- Steven Holzner, Tata McGraw- Hill T3-Web Programming, building internet applications, Chris Bates 2nd edition. T4- The Complete Reference java2 fifth edition by Patrik Naughton and Herbert Schild, TMH. T5- Java Server Pages- Hans Bergsten, SPD O’Reilly. WEB REFERENCES http://www.coreservlets.com. http://www.serverside.com. http://www.roseindia.net/java/ http://www.roseindia.net/servlets/ http://www.w3schools.com
  • 9. UNIT-I Introduction to PHP:( part 1)  Declaring variables  Data types  Arrays  Strings  Operators  Expressions  Control structures  Functions
  • 10. Introduction to PHP: (part2)  Reading data from web form controls like text boxes, radio buttons, lists etc,.  Handling File uploads  Connecting to database (MYSQL as reference), executing simple queries, handling results, handling sessions and cookies.  File Handling in PHP: File operations like opening, closing, reading, writing, appending, deleting etc., on text and binary files listing directories.
  • 11. UNIT-I Introduction to PHP: What is PHP? PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source server side scripting language PHP scripts are executed on the server PHP is free to download and use
  • 12. Introduction to 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
  • 13. Introduction to PHP: Why PHP? PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP supports a wide range of databases PHP is easy to learn and runs efficiently on the server side
  • 14. PHP Installation To start using PHP, you can: Find a web host with PHP and MySQL support Install a web server on your own PC, and then install PHP and MySQL The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/en/install.php
  • 15. PHP Syntax: A PHP script is executed on the server, and the plain HTML result is sent back to the browser. Basic PHP Syntax <?php // PHP code goes here ?>
  • 16. PHP Syntax: The default file extension for PHP files is ".php". A PHP file normally contains HTML tags, and some PHP scripting code. An example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page:
  • 17. Example PHP code: <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello World!"; ?> </body> </html> Output: My first PHP page Hello World
  • 18. Comments in PHP code: PHP supports Single line and Multiline Comments <!DOCTYPE html> <html> <body> <?php // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ // You can also use comments to leave out parts of a code line $x = 5 /* + 15 */ + 5; echo $x; ?> </body> </html>
  • 19. Case Sensitivity in PHP code: In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. In the example below, all three echo statements below are legal (and equal): <!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> </body> </html>
  • 20. Case Sensitivity in PHP code: However, In PHP, variable names are case-sensitive. In the example below, all three variable names are not equal: <!DOCTYPE html> <html> <body> <?php $color = "red"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> </body> </html> Output: My car is red My house is My boat is
  • 21. PHP Variables: Variables are "containers“ for storing information. Creating (Declaring) PHP Variables In PHP, a variable starts with the $ sign, followed by the name of the variable: <!DOCTYPE html> <html> <body> <?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?> </body> </html>
  • 22. PHP Variables: After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5. Note: When you assign a text value to a variable, put quotes around the value. Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
  • 23. PHP Variables: A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for 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 (A-z, 0-9, and _ ) Variable names are case-sensitive ($age and $AGE are two different variables)
  • 24. PHP Variables: Output Variables The PHP echo statement is often used to output data to the screen. The following example will show how to output text and a variable: Example1 <?php $txt = "W3Schools.com"; echo "I love $txt!"; ?> Example 2 <?php $txt = "W3Schools.com"; echo "I love " . $txt . "!"; ?> Example 3 <?php $x = 5; $y = 4; echo $x + $y; ?>
  • 25. PHP ”echo” and “print” Statements: In PHP there are two basic ways to get output: echo and print. 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.
  • 26. PHP ”echo” and “print” Statements: The PHP echo Statement The echo statement can be used with or without parentheses: echo or echo(). Display Text Display variable Example1 <?php echo "This ", "string ", "was ", "made ", "with multiple parameters."; echo "<h2>PHP is Fun!</h2>"; ?> Example 2 <?php $x = 5; $y = 4; echo $x + $y; ?>
  • 27. The PHP print Statement: The print statement can be used with or without parentheses: print or print(). Display Text Display variable Example1 <?php print "<h2>PHP is Fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!"; ?> Example 2 <?php $txt1 = "Learn PHP"; $txt2 = "W3Schools.com"; $x = 5; $y = 4; print "<h2>" . $txt1 . "</h2>"; print "Study PHP at " . $txt2 . "<br>"; print $x + $y; ?>
  • 28. PHP Data Types PHP has a total of eight data types which we use to construct our variables − Integers − are whole numbers, without a decimal point, like 4195. Doubles − are floating-point numbers, like 3.14159 or 49.1. Booleans − have only two possible values either true or false. NULL − is a special type that only has one value: NULL. Strings − are sequences of characters, like 'PHP supports string operations.' Arrays − are named and indexed collections of other values. Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class. Resources − are special variables that hold references to resources external to PHP (such as database connections).
  • 29. PHP Data Types (Integers) Integers − are whole numbers, without a decimal point, like 4195. 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 three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
  • 30. PHP Data Types (Integers) Example:int Example: float Output: int(5985) output: float(10.5985) The PHP var_dump() function returns the data type and value <?php $x = 5985; var_dump($x); ?> <?php $x = 10.5985; var_dump($x); ?>
  • 31. PHP Data Types (NULL) Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. Tip: If a variable is created without a value, it is automatically assigned a value of NULL. Variables can also be emptied by setting the value to NULL: Example:NULL The PHP var_dump() function returns the data type and value <?php $x = "Hello world!"; $x = null; var_dump($x); ?> output: NULL
  • 32. PHP Data Types (Arrays) An array stores multiple values in one single variable. Example: Array Output: array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" } <?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?>
  • 33. PHP Data Types (Arrays) An array stores multiple values in one single variable. Example: Array Output: array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" } <?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?>
  • 34. PHP Data Types (Objects) 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
  • 35. PHP Data Types (Objects) Example: <?php class Car { function Car() { $this->model = "VW"; } } // create an object $herbie = new Car(); // show object properties echo $herbie->model; ?> Output: VW
  • 36. PHP Arrays An array is a data structure that stores one or more similar type of values under a single name. And you can access the values by referring to an index number. For example: if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
  • 37. PHP Arrays Create an Array in PHP In PHP, the array() function is used to create an array: array();
  • 38. PHP Arrays In PHP, 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
  • 39. PHP Arrays (Indexed arrays) There are two ways to create indexed arrays: •The index can be assigned automatically (index always starts at 0), like this: $cars = array("Volvo", "BMW", "Toyota"); or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
  • 40. PHP Arrays(Indexed Arrays) The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values: <?php $cars = array("Volvo", "BMW", "Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> Output: I like Volvo, BMW and Toyota.
  • 41. PHP Arrays(Indexed Arrays) Get The Length of an Array – The count() function is used to return the length (the number of elements) of an array: Example: <?php $cars = array("Volvo", "BMW", "Toyota"); echo count($cars); ?>
  • 42. PHP Arrays(Indexed Arrays) Loop Through an Indexed Array To loop through and print all the values of an indexed array, you could use a for loop, like this: Example: <?php $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?>
  • 43. PHP Arrays(Associative Arrays) The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values. Example: To store the salaries of employees in an array, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
  • 44. PHP Arrays(Associative Arrays) Example: <html> <body> <?php /* First method to create associate array. */ $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500); echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; echo "Salary of qadir is ". $salaries['qadir']. "<br />"; echo "Salary of zara is ". $salaries['zara']. "<br />"; /* Second method to create array. */ $salaries['mohammad'] = "high"; $salaries['qadir'] = "medium"; $salaries['zara'] = "low"; echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; echo "Salary of qadir is ". $salaries['qadir']. "<br />"; echo "Salary of zara is ". $salaries['zara']. "<br />"; ?> </body> </html>
  • 45. PHP Arrays(Multidimensional Arrays) A multi-dimensional 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. Values in the multi-dimensional array are accessed using multiple index. Example In this example we create a two dimensional array to store marks of three students in three subjects −
  • 46. PHP Arrays(Multidimensional Arrays) Example: <html> <body> <?php $marks = array( "mohammad" => array ( "physics" => 35, "maths" => 30, "chemistry" => 39 ), "qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ), "zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) ); /* Accessing multi-dimensional array values */ echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . "<br />"; echo "Marks for qadir in maths : "; echo $marks['qadir']['maths'] . "<br />"; echo "Marks for zara in chemistry : " ; echo $marks['zara']['chemistry'] . "<br />"; ?> </body> </html>
  • 47. PHP Strings Def: A string is a sequence of characters, like "Hello world!". Example: Following are valid strings $string_1 = "This is a string in double quotes"; $string_2 = "This is a somewhat longer, singly quoted string"; $string_39 = "This string has thirty-nine characters"; $string_0 = “ "; // a string with zero characters Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences
  • 48. PHP Strings Example <?php $variable = "name"; $literally = 'My $variable will not print!n'; print($literally); print "<br />"; $literally = "My $variable will print!n"; print($literally); ?> Output: My $variable will not print!n My name will print!n
  • 49. PHP Strings Functions The PHP strlen() function returns the length of a string. The PHP strrev() function reverses a string: The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE. The PHP str_replace() function replaces some characters with some other characters in a string. strcmp() Compares two strings (case-sensitive) strcasecmp() Compares two strings (case-insensitive) str_word_count() Count the number of words in a string strncmp() String comparison of the first n characters (case-sensitive)..etc.
  • 50. PHP String Functions Examples <?php echo strlen("Hello world!"); ?> // outputs 12 <?php echo str_word_count("Hello world!"); ?> // outputs 2 <?php echo strrev("Hello world!"); ?> // outputs !dlrow olleH <?php echo strpos("Hello world!", "world"); ?> // outputs 6
  • 51. PHP Operators Operators are used to perform operations on variables and values. Arithmetic operators Assignment operators Comparison operators Increment/Decrement operators Logical operators String operators Array operators
  • 52. PHP Operators(Arithmetic operators) 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 (Introduced in PHP 5.6)
  • 53. PHP Operators(Assignment operators) 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
  • 54. PHP Operators(Comparison operators) 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
  • 55. PHP Operators(Increment/Decrement operators) The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value. Operator Name Description ++$x Pre-increment Increments $x by one, then returns $x $x++ Post-increment Returns $x, then increments $x by one --$x Pre-decrement Decrements $x by one, then returns $x $x-- Post-decrement Returns $x, then decrements $x by one
  • 56. PHP Operators(Logical operators) The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's value. Operator Name 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
  • 57. PHP Operators(String operators) 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
  • 58. PHP Operators(String operators) Ex1: Ex2:<!DOCTYPE html> <html> <body> <?php $txt1 = "Hello"; $txt2 = " world!"; echo $txt1 . $txt2; ?> </body> </html> Output: Hello world! <!DOCTYPE html> <html> <body> <?php $txt1 = "Hello"; $txt2 = " world!"; $txt1 .= $txt2; echo $txt1; ?> </body> </html> Output: Hello world!
  • 59. PHP Operators(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
  • 60. PHP Operators(Array operators) Ex1: + operator Ex2: === operator <!DOCTYPE html> <html> <body> <?php $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); print_r($x + $y); // union of $x and $y ?> </body> </html> Output: Array ( [a] => red [b] => green [c] => blue [d] => yellow ) <!DOCTYPE html> <html> <body> <?php $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); var_dump($x === $y); ?> </body> </html> Output: bool(false)
  • 61. PHP Control Structures PHP Control Structures are categorized into two types: Conditional Statements Looping Statements
  • 62. PHP Control Structures(Conditional Statements) Conditional statements are used to perform different actions based on different conditions. In PHP we have the following conditional statements: if statement - executes some code if one condition is true if...else statement - executes some code if a condition is true and another code if that condition is false if...elseif....else statement - executes different codes for more than two conditions switch statement - selects one of many blocks of code to be executed
  • 63. PHP Control Structures(Conditional Statements) PHP - The if Statement The if statement executes some code if one condition is true. Syntax if (condition) { code to be executed if condition is true; } The example below will output "Have a good day!" if the current time (HOUR) is less than 20: Example <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?>
  • 64. PHP Control Structures(Conditional Statements) PHP - The if...else Statement The if....else statement executes some code if a condition is true and another code if that condition is false. Syntax if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
  • 65. PHP Control Structures(Conditional Statements) PHP - The if...else Statement The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise: Example: <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
  • 66. PHP Control Structures(Conditional Statements) PHP - The if...elseif....else Statement The if....elseif...else statement executes different codes for more than two conditions. Syntax: if (condition) { code to be executed if this condition is true; } elseif (condition) { code to be executed if this condition is true; } else { code to be executed if all conditions are false; }
  • 67. PHP Control Structures(Conditional Statements) PHP - The if...elseif....else Statement Example: <?php $t = date("H"); if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
  • 68. PHP Control Structures(Conditional Statements) The switch statement is used to perform different actions based on different conditions. The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax: switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; }
  • 69. PHP Control Structures(Conditional Statements) Example: <?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!"; } ?>
  • 70. PHP Control Structures(Looping Statements) PHP while loops execute a block of code while the specified condition is true. PHP Loops: In PHP, we have the following looping statements: 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
  • 71. PHP Control Structures(Looping Statements) The PHP while Loop The while loop executes a block of code as long as the specified condition is true. Syntax: Ex: while (condition is true) { code to be executed; } <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>
  • 72. PHP Control Structures(Looping Statements) The PHP do…while Loop The while loop executes a block of code as long as the specified condition is true. Syntax: Ex: do { code to be executed; } while (condition is true) ; <?php $x = 1; do { echo "The number is: $x <br>"; $x++; } while($x <= 5) ; ?>
  • 73. PHP Control Structures(Looping Statements) PHP for loops execute a block of code a specified number of times. The PHP for Loop The for loop is used when you know in advance how many times the script should run. Syntax: for (init counter; test counter; increment counter) { code to be executed; } Parameters: init counter: Initialize the loop counter value test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value
  • 74. PHP Control Structures(Looping Statements) PHP for loops execute a block of code a specified number of times. The PHP for Loop Example: Output: <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?> 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
  • 75. PHP Control Structures(Looping Statements) The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
  • 76. PHP Control Structures(Looping Statements) The PHP foreach Loop Example <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>