0% found this document useful (0 votes)
143 views37 pages

Unit-1 Introduction To PHP

Uploaded by

carpluswebsite
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views37 pages

Unit-1 Introduction To PHP

Uploaded by

carpluswebsite
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Master in Computer Application (Semester – I) |

Prof. Amit Rathod


(BCA, MCA)
---------- INDEX ----------
[Link]. Topic Name Page No.
UNIT – 1 INTRODUCTION TO PHP
1 Introduction to Static and Dynamic Websites
2 Introduction to PHP
3 History of PHP
4 Basic PHP Syntax
5 PHP File structure
6 Output Statements: echo and print
7 PHP variable and value types
8 PHP constants and magic constants
9 PHP operator and their precedence
 Arithmetic operators
 Increment – decrement operators
 Assignment operators
 Logical operators
 Bitwise operators
 Comparison operators
10 Decision-making statements:
 If statement
 If-else statement
 Else-if clause
 Switch-case statement
 The ? operator
11 Loops:
 While loop
 For loop
 Foreach loop
 Nesting loops
12 Break and Continue statement
Unit – 2 Array and Function in PHP
13 Introduction to PHP Arrays and Types of Arrays:
 Indexed Array
 Associative Array
 Multidimensional Array
14 PHP Strings:
 Single quoted
Prepared By: Prof. Amit Rathod Page No.2
 Double quoted
 Heredoc syntax
 Nowdoc syntax
15 Creating, Manipulating and traversing different types of
Array
16 User defined function:
 Create a function
 Calling a function
 Returning value from function
17 Function with default arguments, passing arguments by
value and reference
18 Variable scope, accessing global variable inside a function
19 Variable function
20 Using PHP built-in functions
 String processing functions:
char( ), ord( ), strlen( ), trim( ), ltrim( ), rtrim( ), join( ),
substr( ), str_replace( ), str_split( ), str_word_count( ),
strcmp( ), strcasecmp( ), strops( ), stripos( ), strrev( ),
strtolower( ), strtoupper( ), str_shuffle( )
 Mathematical functions:
abs( ), ceil( ), floor( ), round( ), rand( ), min( ), max( ),
pi( ),pow( ),sqrt( ), exp( ), log( ), decbin( ), decoct( ),
dechex( ), sin( ), cos( ), tan( ), deg2rad( ), rad2deg( )
 Date/time function:
getdate( ), gettimeofday( ), time( ), date_create( ),
mktime( ), date_format( ), date_diff( ), checkdate( )
Unit-3 Object Oriented Concept in PHP
21 OOP concepts:
 Class
 Object
 Properties
 Methods
 Encapsulation
 Access modifiers
22 Creating classes, objects
23 Constructors and destructors
24 Inheritance
25 Polymorphism: Overloading, Overriding
26 Interface
27 Abstract Class
Prepared By: Prof. Amit Rathod Page No.3
28 Final Keyword
29 Cloning Objects
Unit – 4 forms Handling, Session, Cookies
30 Form Controls:
Text Box, Textarea, List Box, Dropdown, Check Box, Radio
Box, Buttons, Upload, Color, Date etc.
31 Retrieving form data using GET and POST methods
32 Form Validation Using PHP
33 Working with multiple forms
 A web page having multiple forms
 A form having multiple submit buttons
34 Session:
 creating a session
 storing and accessing session data
 destroying session
35 Cookies:
 Setting a cookies
 Accessing cookies data
 Destroying cookies
Unit -5 Working with Database in PHP
36 Introduction to MySQL Database with PHP
37 Creating a database using phpMyAdmin & console
38 Connecting with MySQL database
39 Executing MySQL queries
40 Performing database operations
 Create/delete a table
 Insert data into the table
 Update data into the table
 Retrieve data from the table
 Delete data from the table
41 Displaying data from the database in different formats,
including tables
42 Working on mini-project: Developing simple web
application and hosting it on webserver.

Prepared By: Prof. Amit Rathod Page No.4


Unit – 1: Introduction to PHP

Introduction to Static and Dynamic Websites.


 What is Website?
 Web is a collection of files known as web pages.
 Static Website:
 A Static Website contains Web pages with fixed content.
 Each page is coded in HTML and displays the same information to every
visitor.
 Dynamic Website:
 Dynamic Website contains Web pages that are generated in real-time.

Difference between Static and Dynamic Websites.

Static Website Dynamic Website


A Website whose pages are coded in A Website whose web pages are
HTML and the content of each page is generated in real time.
fixed and does not change unless it is
edited and republished.
Developed using client side technologiesDeveloped using client side technologies
such as HTML and CSS. as well as server side scripting
languages.
Content remain unchanged unless it is Content changes according to client
changed from source code. request.
Simple and easier to program. More complex and difficult program.
Does not allow many user interactions. Allow more user interaction.
Does not access database. Access information from a database.
Cheaper to host. Costly to host.
Difficult to update Easier to update
Used for small scale websites that does Suitable for large scale e-commerce and
not required continuous changes. social media websites.

Prepared By: Prof. Amit Rathod Page No.5


Introduction to PHP.
 PHP stands for: Hypertext Preprocessor.
 It was created by Rasmus Lerdorf in 1994.
 It was previously known as Personal Home Page.
 DEFINATION:
 “PHP is a Scripting Language that is combined with HMTL, either by
embedding it within a Web document or by using it as a file that is
processed alongside it, but on the server side.”

 “PHP is an open-source, server-side, HTML- embedded Web-scripting


language for building dynamic and interactive Web sites.”
 PHP programs run on a Web Server.
 One of the key features of PHP is that you can embed PHP code within HTML
Web pages, making it very easy for you to create dynamic content quickly.
 It flexibility and relatively small learning curve make it one of the most popular
scripting languages around.
 PHP is free to download and use.

History of PHP.
 PHP was created by Rasmus Lerdorf in 1994.
 He released PHP to the general public in 1995, and called it PHP version2.
 In 1997, Zeev Suraski and Andi Gutmans rewrote most of PHP along with
Rasmus, and released PHP version 3.0 in June 1998.
 PHP 4, was launched in May 2000. This version included session handling
features, output buffering, a richer core language, and support for a wider variety
of Web server platforms.
 PHP 5, released in July 2004 supports object – oriented programming (OOP)
implementation, with private and protected class members; final, private,
protected, and static methods; abstract classes; interfaces; and standardized
constructor/ destructor syntax.

Fundamental Features of PHP (Advantages of PHP).


 Server-side Scripting Language:
 PHP is a Server-side Scripting Language.
 It is used in website design which involves embedding scripts in an HTML
source code which results in a user's (client's) request to the server website
being handled by a script running on the server-side before the server
responds to the client's request.

Prepared By: Prof. Amit Rathod Page No.6


 Cost:
 PHP costs you nothing.
 It is open source software and doesn’t need to purchase it for development.
 Easy Use:
 PHP is easy to learn, compared to the others.
 A lot of Ready – made PHP scripts are freely available in market so, you can
use them in your project or get some help from them.
 HTML –Support:
 PHP is a embedded within html; in other words, PHP pages are ordinary
HTML pages that escape into PHP mode only when necessary.
 When a client requests these pages, the web server preprocesses it point.
 These means it goes through the page from top to bottom looking for sections
of PHP, which it will try to resolve.
 PHP is easily embedded with HTML.
 Cross Platform Compatibility:
 PHP and MYSQL run native on every popular flavor of UNIX and Windows.
 A huge percentage of the world’s HTTP servers run on one of these two
classes of operating system.
 So PHP is platform independence (Technology neutral).
 PHP is Compatible with the three leading Web servers:
 Apache HTTP server for UNIX and Windows, Ms Internet Information server
and Netscape Enterprise server.
 It also works with several lesser known servers, including Alex Blits’ fhttpd,
Micro soft’s Personal Web server, AOL servers and Omnicentrix’s Omniserver
application servers.
 Stability:
 The word stable two different thinks in this context.
 The server does not need to be rebooted often.
 PHP does not change radically and incompatibly from release to release. To
our advantage, both of this applies to both MySQL and PHP.
 Speed:
 PHP is pleasingly zipping in its execution, especially when compile as an
Apache module on the UNIX side. In this way, PHP is a fast & Stable Language.
 PHP is very useful in social networking website.
 PHP is a popular Language.
 PHP is no complicated Language because it is very similar to C Language.
 PHP is a Loosely Typed Language.
 Example:
$a;
$a=”ABC”; //variable a will become of String Type
$a=8; //variable a will become of int Type
$a=9.7; //variable a will become of Float Type
Prepared By: Prof. Amit Rathod Page No.7
 PHP is easy to use but extremely powerful Language.
 PHP is not tag based Language.

How PHP Works?


 PHP is server side scripting language this means that the script code is
processed on the web server (Apache or IIS) rather than on client side (i.e.
Client Browser).
 Only processed output is presented to the client in html format.
 To make sure this run the above code in browser like internet explorer and then
right click and choose view source option and observe that no php code is
displayed only processed output is displayed.
 PHP sits between your browser and the web server.
 When you type in the URL of a PHP website in your browser, your browser sends
a request to the web server.
 The web server then calls the PHP script on that page.
 The PHP module executes the script, which then sends the result in the form of
HTML back to your browser, which you see on the screen.
 Here is a basic php diagram which illustrates the process.
S
PHP
E
Sends R
HTML V
Browser E
R

Basic PHP Syntax and file Structure.


 The file must have the .php extension. If the file has an .html extension, the PHP
code will not be executed.
 A PHP scripting block always starts with <?php and ends with ?>.
 A scripting code can be placed anywhere in the document between <?php and ?>.
 It can be used any number of time in web page.
 Syntax:
<?php
// PHP code
?>
 Example:
<?php
echo “Welcome to the World of PHP.”;
?>
Prepared By: Prof. Amit Rathod Page No.8
 A PHP file normally contains HTML tags and some PHP scripting code.
 Below, we have an example of a simple PHP file, with PHP script that uses a
built in PHP function “echo” to output the text “welcome to the world of
PHP” on web page.
<html>
<head>
<title>Example of PHP file </title>
</head>
<body>
<?php
echo “Welcome to the World of PHP.”;
?>
</body>
</html>
 Output:
Welcome to the World of PHP.

PHP start and end tags.


 There are four different pairs of opening and closing tags which can be used in
php.
 Two of those, <?php ?> and <script language=”php”> </script>, are always
available.
 The other two are short tags and ASP style tags, and can be turned on and off
from the [Link] configuration file.
 Below we have an example of a simple PHP script which sends the text
“Hello World” to the browser.
1) Standard PHP Tags:
<?php
echo “Hello World”;
?>
 Each code line in PHP must end with a semicolon.
 In the example above we have used the echo statement to output the text
“Hello World”.
2) Script Tags:
<script language=”php”>
echo “Hello World”;
</script>
3) Short Tags:
<?
echo ”Hello World”;
?>
Prepared By: Prof. Amit Rathod Page No.9
 Short tags are only available when they are enabled via the
short_open_tag [Link] configuration file directive, or if php was
configured with the enable-short-tags option.
4) ASP Style Tags:
<%
echo “Hello World”;
%>
 ASP style tags are only available when they are enabled via the asp_tag
[Link] configuration file directive.
 I recommend that you use the standard form (<?php ?>) rather than the
shorthand from so as not to create confusion which scripting language
has been used for coding the web page.
<?php
?>

Output statements: echo and print


 The echo and print both are used to output data on screen.
1) Echo:
 The simplest use of echo is to print a string as argument.
 For example, echo “Hello World”; or equivalently echo (“Hello World”);
 You can also give multiple arguments to the unparenthesized version of
echo , separated by commas:
echo “Hello”, “World”;
 The parenthesized version, however, will not accept multiple arguments:
echo (“Hello”, “World”);

2) Print:
 The command print is very similar to echo, with two important differences:
 Print can accept only one argument.
 Print returns a value, which represents whether the print statement
succeeded.
 The value return by print will be 1 if the printing was successful and 0 if
unsuccessful.
 For example, the following two lines will print exactly the same thing:
 Print(“3.14159”); //print a string
 Print(3.14159); //print a number

Prepared By: Prof. Amit Rathod Page No.10


Difference between echo and print

echo print
It can accept multiple expressions. It cannot accept multiple expressions.
It is faster than print. It is slower than echo.
echo is not a function. print is function.
It can pass multiple string separated as (,). It cannot pass multiple arguments.

Syntax: Syntax:
void echo (string $arg1 [,string $arg2…]) int print (string $arg)

echo does not return any value. print return 1 or 0 depending on the
success.
Example: Example:
echo ‘Welcome’ , ‘to’ , ‘the world’ print(‘welcome to the world’)

Comment in PHP.
 A comment is the portion of a program that exists only for the human reader.
 PHP also support comment like C, C++, and Java language.
 PHP supports two types of Comments.
 In PHP, we use // or # to make a single-line comment or /* and */ to make a
large comment block (multiline comment).
 Single line comment:
 Single line comment start with “// “symbol.
 “#” symbol is another option used to display single line comment.
 Multiline comment:
 Multiline comment started with symbol /* and end with symbol */.
 Example:
<html>
<body>
<?php
//This is a single line comment
#This is single line comment

/* This is a multiline
Comment block */
?>
</body>
</html>

Prepared By: Prof. Amit Rathod Page No.11


Creating and Saving a PHP file
 To create and run PHP page we need to have PHP installed on the system.
 After that you can create and run PHP pages on your web server.
 To create PHP page you can use any simple editor like notepad or rich editor like
Macromedia Dreamweaver, Sublime Text, VS Code, Notepad++.
 The page must be saved with the extension .php
 How to save your PHP pages:
 If you have PHP inserted into your HTML and want the web browser to
interpret it correctly, then you must save the file with a .php extension,
instead of the standard .html extension.
 So be sure to check that you are saving your files correctly.
 Also the php code should be surrounded with <?php …. ?> tags.
<?php
//your php code goes here
?>
 PHP is a web scripting language which means it was designed to work with
HTML.
 You can easily embed PHP code into your HTML code.

PHP variables and value types


 “Variable are nothing but identifiers which point to a memory location
(RAM) in which data is stored.”
 “A variable is a holder for a type of data. So, based on its type, a variable can
hold numbers, strings, Booleans, objects, resources or it can be NULL.”
 In php variable are quite different from compiled language such as C and Java.
Because of php variables are weakly (loosely) type.
 Syntax :
$var_name = value;
 New PHP programmers often forget the $ sign at the beginning of the variable. In
that case it will not work.
 Example :
<?php

$name = "Well Come to Fun World"; //String type Variable

$number = 19; // Numeric type Variable

$fnumber=19.50 // Floating Type Variable

?>

Prepared By: Prof. Amit Rathod Page No.12


 Here are most important things to know about variables in PHP.
 All variables in PHP lead (start) with dollar sign ($).
 Variables are assigned with the = operator.
 Variables in PHP do not have intrinsic types – a variable does not know in
advance whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default value.
 PHP automatically converts types from one to another when necessary.

 Variable Naming Rules:


 A variable name must start with a letter or an underscore “_”.
 A variable name can only contain alpha-numeric character and
underscores (a-z,0-9, and _).
 A variable name should not contain spaces. If a variable name is more than
one word, it should be separated with underscore ($my_string), or with
capitalization ($myString).
 A string variable is used to store and manipulate a piece of text.
 The following characters are not allowed in variable name.

Character Description
* Asterix
+ Plus
# Hash
@ At the rate
- Minus
& Ampersand
£ Pound

Strings in PHP
 String variables are used for a value that contains character strings.
 After we create a string we can manipulate it.
 A string can be used directly in a function or it can be stored in a variable.
 Below, the PHP script assigns the string "Hello World" to a string variable
called $txtmsg:
<?php
$txtmsg="Hello World";
echo $txt;
?>
 The output of the code above will be:
Hello World

Prepared By: Prof. Amit Rathod Page No.13


The Concatenation Operator
 There is only one string operator in PHP.
 The concatenation operator (.) is used to put two string values together.
 To concatenate two variables together, use the dot (.) operator:
<?php
$txt1="Well Come To";
$txt2="GMIT";
echo $txt1 . " " . $txt2;
?>
 The output of the code above will be:
Well Come To GMIT
 If we look at the code above you see that we used the concatenation operator two
times. This is because we had to insert a third string.
 Between the two string variables we added a string with a single character, an
empty space, to separate the two variables.

Data Types in PHP


 “Which kind of data that variable can hold is known as data type.”
 A variable’s data type determines what operation can be carried out on the
variable’s data, as well as the amount of memory needed to hold the data.
 PHP is loosely typed server side scripting language.
 It means that it automatically determines the data type at the time data is
assigned to each variable.
 In one instance, a variable can hold a string and then later in the script it can hold
an integer or some other data type.
 PHP supports following data type.
1) Scalar data type:
 Scalar data means data that contains only a single value.

Scalar data type Description Example


Integer A whole numbers. Without 25
decimal point.
Float A floating point numbers. 3.14159, 50.15
String A sequence of characters. “Well come to GMDC”
Boolean Only two possible values either TRUE
true or false.

Prepared By: Prof. Amit Rathod Page No.14


2) Compound data type:
 Compound data is data that contains more than one value.
Compound data type Description
Array Arrays are named and indexed collections of
other values.
Object Object are instances of programmer- defined
classes, which can package up both other kind of
values and functions that are specifics to the
class.

3) Special data type:


 PHP supports two special data types. It called special data type because
they don’t contain scalar or compound data, but have specific
meaning.
Special data type Description
Null A special type that only has one value: NULL (does not
contain any value.)
Resources or Contains a reference to an external resource, such as
database file, database connection.

Type Casting in PHP


1) gettype():
 This function is used to get the type of variable. It means this function will
return the type of the PHP variable.
 Syntax:
gettype(arg);
 The above function will return a string representing the type of arg:
integer, float, string, array and object, NULL or unknown type.
 Example:
<?php
$a=10;
echo gettype($a);
echo"<br>";
$str="GMIT";
echo gettype($str);
?>
 Output:
integer
string

Prepared By: Prof. Amit Rathod Page No.15


2) settype():
 The settype() function is used to set the type of a variable.
 Syntax:
settype(var_name, var_type);
 var_name: The variable being converted.
 var_type: Type of variable. Possible values: boolean, integer, float, string,
array, object, NULL.
 Example:
<?php
$a=10;
echo gettype($a);
echo "<br>";
settype($a,"string");
echo gettype($a);
?>
 Output:
 integer
 string

3) Changing data types with casting:


 If you want to change a value’s type at the time you use the value, then you
can use casting.
 Syntax:
(type)variable_name
 Where, type is a type of variable you wish to cast too.
 Example:
<?php
$var1=10;
$var2= (string)$var1;
echo gettype($var2);
?>
Note: var_dump ($var); is used to display the variable type and value.

Prepared By: Prof. Amit Rathod Page No.16


PHP Constants
 A constant is an identifier (name) for a simple value.
 Value of constant cannot change during the execution of the script (except
for magic constants, which aren’t actually constants).
 A constant is case-sensitive by default.
 By convention, constant identifiers are always in uppercase.
 Once a constant is defined, it can never be changed or undefined.
 These are the differences between constants and variables:
 Constant do not have a dollar sign ($) before them;
 Constants may only be defined using the define () function, not by simple
assignment.
 Constants may be defined and accessed anywhere without regard to
variable scoping rules.
 Constants may not be redefined or undefined once they have been set.
 Constants may only evaluate to scalar (data that contain single value) value.
 You can define constant by using the define() – function or by using the
const keyword.
 Only scalar data (Boolean, integer, float and string) can be contained in
constants.
 Constants defined using define() function accepts two arguments: the name of
the constant, and its value.
 Syntax:
define (“CONSTANT_NAME”, “value”);
 Where, CONSTANT_NAME: It is the name of the constant, Value: It is any
valid PHP expression without array and object.
 Example:
<?php
define (“PI”,3.14);
define(“AUTHOR”, “Ivan Bayross”);
echo PI; //output: 3.14
echo AUTHOR; //output Ivan Bayross
echo Author;//output: “Author” and issues a notice;
?>
 Defining Constants using the const keyword.
 Syntax:
Const constVariablename=value;
<?php
const STRCONSTANT= “Hello World”;
echo STRCONSTANT;
?>
Prepared By: Prof. Amit Rathod Page No.17
 As opposed to defining constants using define (), constants defined using the
const keyword must be declared at the top-level scope because they are defined
at compile-time.
 This means that they cannot be declared inside functions, loops or if statements.
 A valid constant name start with a letter or underscore, followed by any number
of letters, numbers, or underscores.
 This is valid but should be avoided:
define (“__PI__”,”3.14”);
 The scope of a constant is global. You can access constants anywhere in your
script without regard to scope.
 constant() function:
 As indicated by the name, this function will return the value of the constant.
 This is useful when you want to retrieve value of a constant, but you do not
know it name, ex. it is stored in a variable or returned by a function.
 Example:
<?php
//constant function
define("PI",3.14);
//echo PI;
echo constant("PI");//same thing as the previous line.

?>
 Only scalar data (boolean, integer, float and string) can be contained in
constants.

Magic Constants
 PHP provides a large number of predefined constants to any script which it runs.
 There are seven magical constants that change depending on where they are
used.
 For example, the value of __LINE__ depends on the line that it’s used on in your
script.
 These special constants are case-insensitive.
 A few “magical” PHP constants are given below:

Name Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside
include, the name of the included file is returned.
Since PHP 4.0.2, __FILE__ always contains an
absolute path whereas in older version it contained
Prepared By: Prof. Amit Rathod Page No.18
relative path under some circumstances.
__FUNCTION__ The function name. (added in PHP 4.3.0) As of PHP 5
this constant returns the function name as it was
declared (case-sensitive). In PHP 4 its value is
always lowercased.
__CLASS__ The class name. (added in PHP 4.3.0) As PHP 5 this
constant returns the class name as it was declared
(case-sensitive). In PHP 4 its value is always
lowercased.
__METHOD__ The class method name. (added in PHP 5.0.0) The
method name is returned as it was declared (case-
sensitive).

Operators in PHP
 “Operator is any symbol used to perform an operation on a value.”
 In PHP operators can easily be grouped by function.
 They are used for simple purpose such as assigning value to variables, working
with string, working with numbers, comparing the value of variable and so on.
 PHP operator can be classified into the following three categories:
1) Unary Operator
a) Increment Decrement Operator
b) Negation operator
c) Cast operator
2) Binary Operator
a) Arithmetic Operator
b) Assignment Operator
c) Comparison Operator
d) Logical Operator
e) Bitwise Operator
3) Ternary Operator

1) Unary Operator:
 Unary Operator work on only one operand.
a) Increment Decrement Operator:
 Increment/Decrement operators are unique in the sense that they
operate only on variables and not on any value.

Operator Description
++ Increment by 1
-- Decrement by 1

Prepared By: Prof. Amit Rathod Page No.19


 Example:
$variable++ // post increment
++$variable // pre increment
$variable-- // post decrement
--$variable // pre decrement
 Note: String (when not numeric) are incremented in a different
way. If the last letter is alphanumeric, it is incremented by1. If it
was ‘z’, ‘Z’ or ‘9’ it is incremented to ‘a’, ‘A’ or ‘0’ respectively. And
the next alphanumeric is also incremented in the same way. If there
is no alphanumeric, one is added to the beginning of the string as ‘a’
‘A’ and ‘1’ respectively. Non-numeric string cannot be
decremented.

b) Negation Operators:
 Negation operators appear before their operand—for example,
!$var (! is the operator, $var is the operand).

Operator Name Value


! Logical Negation True if the operand evaluates
to false.
False if the operand evaluates
to true.
~ Bitwise Negation In case of a numeric operand,
the bitwise negation Of its
bitwise representation
(floating-point values are first
converted to integers).
In case of strings, a string of
equal length, in which each
character is the bitwise
negation of its corresponding
character in the original
string.

Prepared By: Prof. Amit Rathod Page No.20


 Example:
<? php
$no1 = 102.50;
$no2 = 80;
$no3 = (~$no1) + (!$no2);
echo “ The sum of Bitwise number 102.50 and logical
number 80 is ” . $no3;
?>
 Output:
The sum of Bitwise number 102.50 and logical number 80 is – 103

c) Cast Operators:
 PHP provides a C-like way to force a type conversion of a value by
using the cast operators.
 The operand appears on the right side of the cast operator, and its
result is the converted type according to the following table.

Operator Changes Type To


int or integer Integer
Float, real or double Floating point
String String
bool or boolean Boolean
Array Array
Object Object

 The casting operators change the type of a value and not the type of
variable.
 Example:
<?php
$numStr = “15.50 Rupees” ;
$numDec = 10.54;
$ numInt = (int) $numStr;
echo “After casting $numStr to Integer ” . $numInt . <”br/”>;
$ numInt = (int) $numDec;
echo “After casting $numDec to Integer ” . $numInt . <”br/”>;
?>

Prepared By: Prof. Amit Rathod Page No.21


 Output :
After casting 15.50 Rupees to Integer 15
After casting 10.54 to Integer 10

2) Binary Operator:
 Binary Operators work on two operand.

a) Arithmetic Operator:
 Arithmetic Operator is used to perform arithmetic operation such
as addition, subtraction, multiplication etc.
 Following are the arithmetic operators used in PHP.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (division remainder)

b) Assignment Operator:
 Assignment operators are used to change the value of the current
variable with the value on the right of the operator.
 The following are assignment operators used in PHP.

Operator Example Is The Same As


= X=Y X=Y
+= X+=Y X=X+Y
-= X-=Y X=X-Y
*= X*=Y X=X*Y
/= X/=Y X=X/Y
%= X%=Y X=X%Y

c) Comparison Operators:
 Comparison operators are used to compare the value of the
variables.
 Comparision operator determines the relationship between two
operands.

Prepared By: Prof. Amit Rathod Page No.22


 The following are comparison operators used in PHP.

Operator Description Example Result


== Equal to 3==9 Returns false
!= Not equal to 3!=9 Returns true
> Greater than 3>9 Returns false
< Less than 3<9 Returns true
>= Greater than or 3>=9 Returns false
equal to
<= Less than or equal 3<=9 Returns true
to
=== Is identical to 3===”9” Returns false
!== Not identical to 3!==”9” Returns true

d) Logical Operators:
 Logical operators first convert their operands to Boolean values
and then perform their respective comparison.
 Logical operators allow you to determine the status of conditions.
 Depending on the condition of a variable different script action can
occur.
 Logical operators are used extensively with PHP decision
structures.
 The following are Logical operators used in PHP.

Operator Description Example Result


&& And (15!=18) && (15==18) Returns
False
|| Or (25!=28) || (25==28) Returns
True
! Not (25!=28) Returns
True

e) Bitwise Operators :
 Bitwise operators perform an operation on the bitwise
representation of their arguments. Unless the arguments are
strings, they are converted to their corresponding integer
representation, and the operation is then performed.
 In case both arguments are strings, the operation is performed
between corresponding character offsets of the two strings (each
character is treated as an integer).
Prepared By: Prof. Amit Rathod Page No.23
Operator Menning Description

& Bitwise The & (bitwise AND) operator compares all


AND the bits in operand one against all the bits
on operand two, then returns a result with
all the joint bits set.

| ,or , Bitwise The | (Bitwise OR) operator compares all


OR the bits in operand one against those in
operand two and returns a result with all
the bits set in either of them.

^ Bitwise The ^ (bitwise XOR) operator compares all


XOR the bits in operand one against those in
(Exclusive operand two and returns a result with all
OR) the bits set in either of them but not both.

 Example :
<?php
$no = 40 ^ 20;
echo "the result is ". $no;
echo "<br/>";
$str1 = "hi" &"hello";
echo "the result is ". $str1;
echo "<br/>";
$no1= 40 & 20;
echo "the result is ". $no1;
echo "<br/>";
$str2 = "hello" |"hi";
echo "the result is ". $str2;
echo "<br/>";
$no2= 40 | 20;
echo "the result is ". $no2;
echo "<br/>";
?>

Prepared By: Prof. Amit Rathod Page No.24


 Output:
the result is 60
the result is ha
the result is 0
the result is hmllo
the result is 60

3) Ternary Operator:
 One of the most elegant operators is the ‘… ? …’ operator.
 Syntax:
<Truth_Expr> ? <Expr1>:<Expr2>
 The operator evaluates Truth_Expr and checks whether it is true.
 If it is, then evaluates to the value of Expr1.
 If it is false, then evaluates to the value of Expr2.
 Example:
<?php
$no1=25;
$no2=30;
echo ($no1>$no2)? "$no1 is Greater.": "$no2 is Greater.";

?>
 Output:
30 is Greater.

Operator Precedence in PHP


 Operator precedence determines the grouping of terms in an expression.
 This affects how an expression is evaluated.
 Certain operators have higher precedence than others.
 For example, the multiplication operator has higher precedence than the addition
operator.
 For example, X=7+3*2;
 Here x is assigned 13 not 20 because operator * has higher precedence than
+ so it first get multiplied with 3*2 and then adds into 7.
 Here operators with the highest precedence appear at the top of the table; those
with the lowest appear at the bottom. Within an expression, higher
precedence operator will be evaluated first.

Prepared By: Prof. Amit Rathod Page No.25


Category Operator Associativity
Unary ! ++ -- Right to Left
Multiplicative */% Left to Right
Additive +- Left to Right
Relational < <= > >= Left to Right
Equality == != Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
Assignment = += -= *= /= %= Right to Left

Decision-making statements in PHP


 The linear, hierarchic, top down, execution of a program, is controlled by
‘Control Structures’ embedded within the program code.
 PHP code often has to do several things, this means that PHP code has to have
decision making abilities, based on the decision made, the PHP code will do some
work or otherwise do something else entirely.
 The if..elseif...else and switch statements are used to take decision based on the
different condition.
 You can use conditional statements in your code to make your decisions.
 PHP supports following four decision making statements:
1) If Statement
2) If...else Statement
3) If…Elseif…else Statement
4) switch Statement

1) If Statement:
 If statement is used to execute some code only if a specified condition is
true.
 It is simple decision making statement.
 Syntax:
If(condition)
{
//code to be executed if condition is true;
}

Prepared By: Prof. Amit Rathod Page No.26


 Example:
<?php
$no1=20;
$no2=30;
if($no1<$no2)
{
echo "No2 is higher.";
}
?>
 Output:
No2 is higher.

2) If...Else Statement:
 If you want to execute some code if a condition is true and another code if
a condition is false, use the if....else statement.
 It is called two way decision making statements.
 Syntax:
if (condition)
{
//code to be executed if condition is true;
}
else
{
//code to be executed if condition is false;
}
 Example:
<?php
$d=date("D");
//echo $d;
if($d=="Fri")
{
echo "Have a Nice Weekend..";
}
else
{
echo "Have a Nice Day..";
}
?>

Prepared By: Prof. Amit Rathod Page No.27


 Output:
Have a Nice Day..

3) If…elseIf…else Statement:
 If…elseif…else statement is used when the number of condition are more.
 It is useful when developer need to check multiple conditions at same
level.
 If first condition is evaluated as false then second condition is checked.
 If second condition is evaluated as false then third condition is checked
and so on.
 If first condition is true then statement-1 executes. And remaining
condition will not be checked.
 If second condition is true then statement-2 executes and remaining
condition will not be checked and so on.
 If all condition are false then statement –x given with else part executes.
 Syntax:
if (condition)
{
Statement -1
//code to be executed if condition is true;
}
elseif (condition)
{
Statement - 2
//code to be executed if condition is true;
}
else
{
Statement - x
//code to be executed if condition is false;
}

 Example:
<?php
$day=date("D");
//echo $day;
if($day=="Fri")
{
echo"Have a Nice weekend..!";
}
else if($day=="Sun")
Prepared By: Prof. Amit Rathod Page No.28
{
echo "Have a nice Sunday..!";
}
else
{
echo "Have a Nice Day..!";
}
?>

4) The Switch Statement:


 If you want to select one of many blocks of code to be executed, use the
Switch statement.
 The switch statement is used to avoid long blocks of if..elseif..else code.
 Syntax:
switch (expression)
{
case label1:
//code to be executed if expression = label1;
break;
case label2:
//code to be executed if expression = label2;
break;
default:
//code to be executed if expression is different from both label1 and
label2;
}
 Example:
<?php
$day=date("D");
switch($day)
{
case "Mon":
echo "Today is Monday.";
break;
case "Tue":
echo "Today is Tuesday.";
break;
case "Wed":
echo "Today is Wednesday.";
break;
case "Thu":
echo "Today is Thursday.";
Prepared By: Prof. Amit Rathod Page No.29
break;
case "Fri":
echo "Today is Friday.";
break;
case "Sat":
echo "Today is Saturday.";
break;
case "Sun":
echo "Today is Sunday.";
break;
default:
echo "Wonder! Which day is this?";

}
?>

Loops in PHP
 Loops in PHP are used to execute the same block of code a specified number of
times.
 PHP supports following four loop types.
1) For loop: loops through a block of code a specified number of times.
2) While loop: loops through a block of code if and as long as a specified
condition is true.
3) Do...while loop: loops through a block of code once, and then repeats the loop
as long as a special condition is true.
4) Foreach loop: loops through a block of code for each element in an array.

1) For loop:
 The for statement is used when you know how many times you want to
execute a statement or a block of statements.
 For this reason, the for loop is known as a definite loop.
 Syntax:
for (initialization; condition; increment/decrement)

code to be executed;

Prepared By: Prof. Amit Rathod Page No.30


 Parameters:
 Initialization: Mostly used to set a counter (start value) (but can be
executed once at the beginning of the loop)
 Condition: The condition expression is evaluated. If the value of
condition is TRUE, the loop statement executes. If the value of condition
is FALSE, the for loop terminates.
 Increment/Decrement: Mostly used to increment/decrement a
counter (but can be any code to executed at the end of the iteration).
 Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>For Loop</title>
</head>
<body>
<?php
for($no=1;$no<=5;$no++)
{
echo "The Value is :".$no."<br>";
}
?>
</body>
</html>
 Output:
The Value is :1
The Value is :2
The Value is :3
The Value is :4
The Value is :5

Prepared By: Prof. Amit Rathod Page No.31


2) While loop:
 While loop is entry control loop that it checks the condition at time of entry
in a loop.
 The while statement will execute a block of code if and as long as a
specified condition evaluates to true.
 Syntax:
while (condition)

code to be executed;

 The block of code associated with the while statement is always enclosed
within the { (opening) and } (closing) brace symbols to tell PHP clearly
which lines of code should be looped through.
 Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>while loop</title>
</head>
<body>
<?php
$no=5;
while($no>=1)
{
echo "The Number is :".$no."<br>";
$no--;
}
?>

</body>
</html>

Prepared By: Prof. Amit Rathod Page No.32


 Output:
The Number is :5
The Number is :4
The Number is :3
The Number is :2
The Number is :1

3) Do...while loop:
 Do…while loop is exit control loop that it checks the condition at time of
exit in loop.
 The do…while statements are similar to while loop, except that the
condition is tested at the end of each iteration, rather than at the beginning.
 This means that the do...while loop will execute a block of code at least
once if condition is FALSE from beginning.
 Syntax:
do
{
code to be executed;
}while (condition);
 Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>do while loop</title>
</head>
<body>
<?php
$no=1;
do
{
echo "The Number is :".$no."<br>";
$no++;
}while($no<=5);
?>
</body>
</html>

Prepared By: Prof. Amit Rathod Page No.33


 Output:
The Number is :1
The Number is :2
The Number is :3
The Number is :4
The Number is :5

4) foreach loop:
 The foreach loop is a variation of the for loop.
 The foreach statement is used to loop through arrays.
 For each pass the value of the current array element is assigned to $value
and the array pointer is moved by one and in the next pass next element
will be processed.
 Syntax:
foreach (array as value)
{
code to be executed;
}
 Example:
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is : $value <br />";
}
?>
</body>
</html>
 Output:
Value is : 1
Value is : 2
Value is : 3
Value is : 4
Value is : 5

Prepared By: Prof. Amit Rathod Page No.34


Break and Continue Statements.
 There are two special statements that can be used inside loops: Break and
Continue.

1) The break statement


 The PHP break keyword is used to terminate the execution of a loop
prematurely.
 The break statement is situated inside the statement block.
 It gives you full control and whenever you want to exit from the loop you
can come out.
 After coming out of a loop immediate statement to the loop will be
executed.
 Example:
<html>
<body>
<?php
$i = 0;
while( $i < 10)
{
$i++;
if( $i == 3 )
{
break;
}
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>

 Output:
Loop stopped at i = 3

2) The continue statement


 The continue statements terminates execution of the block of statements in
a while or for loop and continues execution of the loop with the next
iteration.
 The Continue keyword is used to halt (skip/jump) the current iteration of a
loop but it does not terminate the loop.

Prepared By: Prof. Amit Rathod Page No.35


 Example:
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
if( $value == 3 )
{
continue;
}
echo "Value is $value <br />";
}
?>
</body>
</html>

 Output:
Value is 1
Value is 2
Value is 4
Value is 5

Difference between Break and Continue.

BREAK CONTINUE
Break is used to terminate the execution
Continue is not used to terminate the
of the loop. execution of the loop.
It breaks the iteration. It skips the iteration.
When this statement is executed, control
When this statement is executed, it will
will come out from the loop and executes
not come out from the loop but
the statement immediate after loop. moves/jumps to the next iteration of
loop.
Break is used with loops as well as Continue is only used in loops, it is not
switch case. used in switch case.
Example: Example:
Prepared By: Prof. Amit Rathod Page No.36
<?php <?php
for($no=0;$no<=5;$no++) for($no=0;$no<=5;$no++)
{ {
if($no==3) if($no==3)
{ {
break; continue;
} }
echo "No. :".$no."<br>"; echo "No.:".$no."<br>";
} }
?> ?>
Output: Output:
No. :0 No.:0
No. :1 No.:1
No. :2 No.:2
No.:4
No.:5

Prepared By: Prof. Amit Rathod Page No.37

You might also like