0% found this document useful (0 votes)
31 views31 pages

UNIT 1 PHP and MYSQL

The document provides an introduction to PHP, a widely-used open-source scripting language primarily for web development, detailing its history, features, and functionalities. It explains how PHP works, its syntax, and how to create and execute PHP scripts, along with the necessary software and tools required for development. Additionally, it highlights the advantages of using PHP, such as performance, portability, ease of use, and community support.
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)
31 views31 pages

UNIT 1 PHP and MYSQL

The document provides an introduction to PHP, a widely-used open-source scripting language primarily for web development, detailing its history, features, and functionalities. It explains how PHP works, its syntax, and how to create and execute PHP scripts, along with the necessary software and tools required for development. Additionally, it highlights the advantages of using PHP, such as performance, portability, ease of use, and community support.
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
You are on page 1/ 31

College:Vedanth BCA and Bcom College,Vijayapura

Lecture:Annapoorna Kalloli
Subject:PHP and MySQL

Unit 1
Introducing PHP: Basic development Concepts -Creating first PHP Scripts -Using Variable and Operators -
Storing Data in variable -Understanding Data types -Setting and Checking variables-Data types -Using
Constants -Manipulating Variables with Operators. Subject:PHP and MySQL

Introducing PHP
PHP(Hypertext Preprocessor) is a versatile scripting language primarily used for web development, but
it can indeed be used in multiple ways. PHP started out as a small open source project that evolved as
more and more people found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP
way back in 1995.
 It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.
 It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase,
Informix, and Microsoft SQL Server.
 PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the Unix
side. The MySQL server, once started, executes even very complex queries with huge result sets in
record-setting time.
 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4 added
support for Java and distributed object architectures (COM and CORBA), making n-tier development
a possibility for the first time.
 PHP is forgiving: PHP language tries to be as forgiving as possible.
What is PHP?
PHP is an acronym for (PHP: Hypertext Preprocessor) is a widely-used open source general-purpose
scripting language that is especially suited for web development and can be embedded into HTML. PHP
scripts are executedon the server. PHP files have extension".php".
History of PHP:
PHP history dates back to the early days of the web, and it has gone through several significant
milestones. Here's a brief history of PHP :
1. Creation of PHP/FI (1994): PHP originated in 1994 when Rasmus Lerdorf, a programmer, created a
set of Perl scripts to track visits to his online resume. He later expanded it to handle form data and
interact with databases, naming it "Personal Home Page/Forms Interpreter" or PHP/FI. It was more of
a collection of tools than a programming language.
2. Introduction of PHP2.0(1995):PHP/FI was further developed,and in 1995,PHP2.0 was released.
This version included more advanced features, better support for web forms, and could communicate
with various databases.

3. Birth of PHP 3.0 (1998): PHP 3.0, released in 1998, marked a significant milestone. It was a
complete rewrite of the PHP codebase and introduced the parser written in C, making it more
efficient and faster.PHP3.0 also added support for various databases and improved support for
different web servers.
4. PHP4.0(2000):PHP4.0,released in 2000,was a major step forward in PHP' evolution. It included
enhanced support for object-oriented programming (OOP), better performance, and added numerous
features. PHP was now recognized as a full-fledged scripting language suitable for building dynamic
websites.

5. PHP5.0(2004):PHP5.0,released in 2004,brought even more significant changes. It introduced the


Zend Engine 2, which greatly improved performance and added features like exception handling, and
support for OOP was significantly enhanced with the introduction of classes and interfaces.

6. PHP5.3(2009):PHP5.3,releasedin2009,included features such as namespaces and late static binding,


which made it easier to manage large codebases and improve code organization.

7. PHP5.4(2012):PHP5.4,releasedin2012,focusedonperformanceimprovements,andit introduced short


array syntax, traits,and improvements in syntax and language features.

8. PHP 7.0 (2015): PHP 7.0 was a groundbreaking release in terms of performance. It introduced the
ZendEngine3, which significantly improved PHP's execution speed.The update also included scalar
type declarations, the spaceship operator, and the null coalescing operator.

9. PHP7.4(2019):PHP7.4 brought features like arrow functions, typed properties, and improved
performance.

10. PHP8.0(2020):PHP8.0 introduced several new features ,including the JIT(Just-In-Time)compiler,


union types, and match expressions. It further enhanced performance and language capabilities.

PHP continues to evolve, with regular updates and improvements. It remains a widely used language for web
development, powering countless websites and web applications. Its open-source nature and active
community make it a versatile and robust choice for developers around the world.
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
 PHP code are executed on the server, and the result is returned to the browser as plain HTML.
 PHP files have extension ".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 with PHP you are not limited to output HTML. You can output images, PDF files,
and even flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, MacOSX, etc.).
 PHP is compatible with almost all servers used today(Apache,IIS,etc.).

2
 PHP supports a wide range of databases.
 PHP is easy to learn and runs efficiently on the server side.
 PHP is widely-used.

Unique Features
If you’re familiar with other server-side languages like ASP.NET or JSP, you might bewondering what makes
PHP so special, or so different from these competing alternatives.well, here are some reasons:

Performance :Scripts written in PHP execute faster than those written in other scripting languages, with
numerous independent benchmarks putting the language ahead of competing alternatives like JSP, ASP.NET,
and Perl. The PHP 5.0 engine was completely redesigned with an optimized memory manager to improve
performance, and is noticeably faster than previous versions. In addition, third-party accelerators are available
to further improve performance and response time.

Portability PHP is available for UNIX, Microsoft Windows, Mac OS, and OS/2, and PHP programs are
portable between platforms. As a result, a PHP application developed on, say, Windows will typically run on
UNIX without any significant issues. This ability to easily undertake cross-platform development is a valuable
one, especially when operating in a multiplatform corporate environment or when trying to address multiple
market segments.

Ease of Use :“Simplicity is the ultimate sophistication,” said Leonardo da Vinci, and by that measure, PHP is
an extremely sophisticated programming language. Its syntax is clear and consistent, and it comes with
exhaustive documentation for the 5000+ functions included with the core distributions. This significantly
reduces the learning curve for both novice and experienced programmers, and it’s one of the reasons that PHP is
favored as a rapid prototyping tool for Web-based applications.

Open Source PHP is an open-source project—the language is developed by a worldwide team of volunteers
who make its source code freely available on the Web, and it may be used without payment of licensing fees or
investments in expensive hardware or software.This reduces software development costs without affecting
either flexibility or reliability.The open-source nature of the code further means that any developer, anywhere,
can inspect the code tree, spot errors, and suggest possible fixes; this produces a stable, robust product wherein
bugs, once discovered, are rapidly resolved—sometimes within a few hours of discovery!

Community Support One of the nice things about a community-supported languagelike PHP is the access it
offers to the creativity and imagination of hundreds of developers across the world. Within the PHP community,
the fruits of this creativity may be found in PEAR, the PHP Extension and Application Repository
(http://pear.php.net/), and PECL, the PHP Extension Community Library (http://pecl.php.net/), which contains
hundreds of ready-made widgets and extensions that developers can use to painlessly add new functionality to
PHP. Using these widgets is often a more time- and cost-efficient alternative to rolling your own code.

Third-Party Application Support One of PHP’s strengths has historically been its support for a wide range of
different databases, including MySQL, PostgreSQL, Oracle, and Microsoft SQL Server. PHP 5.3 supports more

3
than fifteen different database engines, and it includes a common API for database access. XML support makes
it easy to read (and write) XML documents as though they were native PHP data structures, access XML node
collections using XPath, and transform XML into other formats with XSLT style sheets.

How PHP works?


 The PHP programmer interacts with the site server, which is the programmer that sends out web pages
to the rest of the world.
 When you type a URL into the address bar of your web browser, you’re telling the web server at that
URL to email you an HTML file.
 The requested file is sent by the web server in response.
 The HTML file is read by your browser, and then shows the web page. When you press a source on a
web page, you’re also requesting a file from the web server. Additionally, when you press a web page
button that submits a form, the web server processes a file.
 When PHP is mounted, the procedure is exactly the same. You submit a file, and the web server, which
happens to be running PHP, responds with HTML, because of PHP it all happens.
You can understand this through these steps:-
Step 1 – Client send a page request to the web server.
Step 2 – Web server forwards that request to the PHP interpreter.
Step 3 – Now PHP interpreter will take the Date from Database and response it back to the Web server.
Step 4 – At last Web server response to the client who has asked for the page request.

From the preceding explanation, it should be clear that to get started building PHP applications, your
development environment must contain at least three components:
● A base operating system (OS) and server environment (usually Linux)
● A Web server (usually Apache on Linux or IIS on Windows) to intercept HTTP requests and either serve
them directly or pass them on to the PHP interpreter for execution
● A PHP interpreter to parse and execute PHP code, and return the results to the Web server
There’s also often a fourth optional but very useful component:

4
● A database engine (such as MySQL) that holds application data, accepts connections from the PHP layer, and
modifies or retrieves data from the database.
An important corollary of this approach is that the PHP code is executed on the server, and
not on the client browser. This allows Web developers to write program code that is completely independent of,
and thus impervious to, browser quirks—an important advantage over client-side scripting languages, such as
JavaScript, which often require complex logic to account for browser-specific differences. Further, because the
code is all executed on the server and only the output is sent to the client, it is impossible for users to see the
source code of your PHP program—an important security advantage over languages like JavaScript.

PHP Syntax:
 A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
 A PHP script can be placed anywhere in the document.
 A PHP script starts with
<?php and ends with ?>

Example:
<?php
echo “Hello World”;
?>
Creating first PHP script
 To get a feel for PHP, first start with simple PHP scripts.
 Writing and Running the Script
 PHP scripts are merely plain-text files containing PHP instructions, sometimes combined with other
odds and ends—JavaScript, HTML, and so on. So, the simplest way to write a PHP script is to pop open
your favorite text editor and create a file containing some PHP code as follow
<?php
echo “Hello World”;
?>
save this file to a location under your Web server’s document root, and name it hello.php. Then, start up your
Web browser, and browse to the URL corresponding to the file location

Understanding Scripting
What happened here? Well, when you requested the script hello.php,the Apache Web server received your
request, recognized that the file was a PHP script (by means of the .php file extension), and handed it off to the
PHP parser and interpreter for further processing. This PHP interpreter then read the instructions between the
<?php ... ?> tags, executed them, and passed the results back to the Web server, which in turn sent them back to
your browser. The instructions in this instance consisted of a call to PHP’s echo statement, which is responsible
for displaying output to the user; the output to be displayed is enclosed in quotation marks.There is some useful
information to be gleaned from even this simple PHP script. It should be clear, for example, that all PHP code
must be enclosed within <?php ... ?> tags and every PHP statement must end in a semicolon. Blank lines within
the PHP tags are ignored by the parser.

5
Softwares Required For To Work With Php:
1. Browser - Internet Explorer
2. Server - Apache
3. Server side script - PHP
4. Database - MYSQL

Tools To Work With Php:


1. XAMPP - Cross Apache MYSQL PHP Perl
2. WAMPP - Window Apache MYSQL PHP Perl
3. LAMPP - Linux Apache MYSQL PHP Perl
4. MAMPP - Macintosh Apache MYSQL PHP Perl

How To Download & Install Xampp Tool?


1. Go to Google
2. XAMPP download in Google Search
3. Select appropriate version of XAMPP based on OS
4. Click on download

Installation
5. Double click on downloaded file
6. Click on the Next button
7. Select drive where you want to installed
8. Click on the Next button until you will get finished button
9. Click on Finish button

How To Start Or Stop Apache Server?


If you would like to run PHP program Apache server should be in start mode. To start or stop Apache server we
have to follow below steps
1. Open XAMPP folder where we installed
2. Select Icon with name called XAMPP Hyper control
3. Double click on the Icon
4. It will open the window, click on start button related to Apache module.

How To Check Xampp S/W Are Successufully Running Or Not?


1. Open any browser
2. Type http://localhost in browser url address and press enter
3. If we can see welcome page XAMPP i.e., running successfully, so that we can start working with PHP

How To Write Php Program


1. Open ant Editor
2. Create a New file
3. Save the file name with extension .php inside “htdocs” folder
C:/XAMPP/htdocs(Ex: abc.php)
6
4. We need to write PHP code inside saved file
Ex: <?php
……..
……..
?>
5. Save again php file

How To Execute Php Program


1. Open any browser
2. Type in the url http://localhost/program.php name and press enter
3. You can see now output if we don’t have any error
Example:
1. Open notepad or any editor and implement PHP script.
<?php
echo “Hello World”;
?>
2. Save this file in htdocs folder with .php extension.
3. To display output, open browser and enter URL address by providing site name with server name.

Mixing PHP with HTML


When the PHP parser reads a script, it executes only the code found between PHP tags; everything outside these
tags is ignored by the parser and returned “as is.” This makesit extremely easy to embed PHP code within an
HTML document to create Web pages that have all the formatting bells and whistles of standard HTML but can
additionally perform complex calculations or read and manipulate data from external sources (suchas databases
or Web services).
Example:"Hello World" Script in PHP”
Since "Hello, World!" is an essential example, first we will create a friendly little "Hello, World!" script.
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php
echo "Hello, World!";
?>
</body>
</html>
It will produce following result –
Hello, World!
If you examine the HTML output of the above example, you'll notice that the PHP code is not present in the file
sent from the server to your Web browser. All of the PHP present in the Web page is client from the Web server
is pure HTML output.

7
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only purpose is to be read
by someone who is looking at the code.
Ex:
// 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 */

PHP Case Sensitivity


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):
Ex:
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
PHP Whitespace Insensitive
 Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and
carriage returns (end-of-line characters).
 PHP whitespace insensitive means that it almost never matters how many whitespace characters you
have in a row.one whitespace character is the same as many such characters.
For example, each of the following PHP statements that assigns
the sum of 2 + 2 to the variable $four is equivalent −
$four = 2 + 2; // single spaces
$four <tab>=<tab>2<tab>+<tab>2 ; // spaces and tabs
$four =
2+
2; // multiple lines

Escaping Special Characters


PHP allows you to escape certain characters by preceding them with a backslash (\). There so-called escape
sequences include

8
When the parser encounters one of these escape sequences, it knows to replace it with the corresponding value
before sending it to the output device.

PHP Variable or Storing Data in Variables


 Variables are "containers" for storing information.
 A variable is simply a container that’s used to store both numeric and non-numeric information.
 Variable is an identifier which holds data or another one variable and whose value can be changed at the
execution time of script.
PHP has some simple rules for naming 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 can't 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 ($str and $STR both are two different)
Example
$root, $_num, and $query2 are all valid variable names, while $58%, $1day, and email are all invalid variable
names.

Assigning Values to Variables


Assigning a value to a variable in PHP is quite easy: use the equality (=) symbol, which also happens to be
PHP’s assignment operator. This assigns the value on the right side of the equation to the variable on the left.
To use a variable in a script, simply call it by name in an expression and PHP will replace it with its value when
the script is executed
Syntax: $variablename=value;
Example
<?php
$str="Hello world!";
$a=5;
$b=10.5;
echo "String is: $str <br/>";
echo "Integer is: $x <br/>";
echo "Float is: $y <br/>";
?>
Output
String is:Hello World!
Integer is:5
Float is:10.5

Variable Scopes
Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the scope of a
variable is the portion of the program with in which it is visible or can be accessed.Depending on the scopes,
PHP has three variable scopes:
9
1. Local variables: The variables declared within a function are called local variables to that function and has
its scope only in that particular function. In simple words it cannot be accessed outside that function. Any
declaration of a variable outside the function with same name as that of the one within the function is a
complete different variable.
Example:
<?php
$num = 60;
function local_var()
{
$num = 50;
echo "local num = $num \n";
}
local_var();
echo "Variable num outside local_var() is $num \n";
?>
Output: local num = 50
Variable num outside local_var() is 60

2. Global variables: The variables declared outside a function are called global variables. These variables can
be accessed directly outside a function. To get access within a function we need to use the “global” keyword
before the variable to refer to the global variable.
Example:
<?php
$num = 20;
function global_var()
{
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Output: Variable num inside function : 20
Variable num outside function : 20

3. Static variable: It is the characteristic of PHP to delete the variable, ones it completes its execution and the
memory is freed. But sometimes we need to store the variables even after the completion of function execution.
To do this we use static keyword and the variables are then called as static variables.
Example:
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
10
?>
Output: 0 1 2

Destroying Variables
 To destroy a variable, pass the variable to PHP’s aptly named unset() function.
 Trying to access or use a variable that’s been unset(), as in the preceding script, will result in a PHP
“undefined variable” error message. This message may or may not be visible in the output page,
depending on how your PHP error reporting level is configured.
Example:
<?php
$var1=100;
echo “value of var1 is $var1”;
echo “<br>”;
unset($var1);
echo “value of var1 is $var1”;
?>
Output
value of var1 is: 100
Warning: Undefined variable $var1 in C:\xampp\htdocs\smallprogram\destroy.php on line 9
value of var1 is:

Inspecting Variable Contents


 PHP offers the var_dump() function, which accepts a variable and X-rays it for you.
 Using var_dump() function, we can display the value of a variable along with data type.
 There’s also a print_r() function that performs the same function as var_dump(), although it returns less
information.
Here’s an example:
<?php
// define variables
$name = 'Vedant';
$age = 28;
// display variable contents
var_dump($name);
var_dump($age);
?>
Output
string(6) "Vedant" int(2) 28

print_r(): Using this function, we can display all elements of array


and properties of object.
Example:
<?php
$x=array(10,20,30);
print_r($x);
?>
Output:
Array
(
[0] => 10
11
[1] => 20
[2] => 30
)

Understanding PHP’s Data Types


 Variables can store data of different types, and different data types can do different things.
 The values assigned to a PHP variable may be of different data types, ranging from simple string and
numeric types to more complex arrays and objects.
PHP supports the following data types:
1. • String
2. • Integer
3. • Float (floating point numbers - also called double)
4. • Boolean
5. • Array
6. • Object
7. • NULL
8. • Resource

1.PHP String
• A string can be any text inside quotes. You can use single or double quotes.
• It can hold letters or any alphabets, even numbers are included.
• The strings can also be written within single quotes but it will be treated differently while printing
variables.
Ex:
<?php $x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output:
Hello world!
Hello world!

2.PHP Integer:
 Integers hold only whole numbers including positive and negative numbers, i.e., numbers without
fractional part or decimal point.
 An integer must have at least one digit
 They can be decimal (base 10), octal (base 8) or hexadecimal (base16).
 The default base is decimal (base 10).
 The octal integers can be declared with leading 0 and the hexadecimal can be declared with leading 0x.
 The range of integers must lie between -2^31 to 2^31.
Example:
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
$sum = $deci1 + $deci2;
12
echo $sum;
?>
Output: 704

In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
Ex:
<?php
$x = 5985;
var_dump($x);
?>
Output: int(5985)

Example:
<?php
$x = 4356; //decimal number
echo $x.' is : ';
var_dump($x);
$x = -39; //a negative number
echo '<br />'.$x.' is : ';
var_dump($x);
$x = 057; //octal number (equivalent to 47 decimal)
echo '<br />'.$x.' is : ';
var_dump($x);
$x = 0x4B; //hexadecimal number (equivalent to 75//decimal)
echo '<br />'.$x.' is : ';
var_dump($x);
?>

Output
4356 is : int(4356)
-39 is : int(-39)
47 is : int(47)
75 is : int(75)

4.PHP Float(or)double
 It can hold numbers containing fractional or decimal part including positive and negative numbers.
 By default, the variables add a minimum number of decimal places.
Example:
<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;
echo $sum;
?>
Output: 705.11

In the following example $x is a float. The PHP var_dump() function returns the data type and value:
Ex:
<?php
13
$x = 10.365;
var_dump($x);
?>
output
float(10.365)

5.PHP Boolean:
 Hold only two values, either TRUE or FALSE.
 Successful events will return true and unsuccessful events return false.
 NULL type values are also treated as false in Boolean.
 If a string is empty then it is also considered as false in Boolean data type.

Example:
<?php
if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>
Output: This condition is TRUE
This condition is not TRUE

6.PHP Arrays:
Array is a compound data-type which can store multiple values of same data type.
Example
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";
?>
Output: First Element: 10
Second Element: 20
Third Element: 30

In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
Ex:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output:
array(3) {
[0]=> string(5) "Volvo"
[1]=> string(3) "BMW"
[2]=> string(6) "Toyota"
}

14
7.PHP Object
 Objects are defined as instances of user defined classes that can hold both values and functions.
 Classes and objects are the two main aspects of object-oriented programming.
 A class is a template for objects, and an object is an instance of a class.
 When the individual objects are created, they inherit all the properties and behaviors from the class, but
each object will have different values for the properties.
 If you create a __construct() function, PHP will automatically call this function when you create an
object from a class.
Example:
<?php
class gfg {
public $message;
function __construct($message) {
$this->message = $message;
}
function msg() {
return "This is an example of " . $this->message . "!";
}
}
$newObj = new gfg("Object Data Type");
echo $newObj->msg();
?>
Output:
This is an example of Object Data Type!
8.PHP 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:
<?php
$nm = NULL;
echo $nm; // This will give no output
?>
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output
NULL
9.Resources:
 The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.
 A common example of using the resource data type is a database call.
15
 We will not talk about the resource type here, since it is an advanced topic
For example, consider a database call. This is an external resource.

Setting and Checking Variable Data Types


Unlike other programming languages, where a variable’s data type must be explicitly defined by the
programmer, PHP automatically determines a variable’s data type from the content it holds. And if the
variable’s content changes over the duration of a script, the language will automatically set the variable to the
appropriate new data type.
The PHP gettype() function returns the type of a variable as a string. It identifies the variable’s data
type, such as string, integer, array, boolean, etc., allowing developers to check and handle different data types
dynamically.
Syntax:
string gettype ( $var )

Parameter: This function accepts a single parameter $var. It is the name of the variable which is needed to
be checked for the type of variable.
Here’s an example of juggling(PHP is known as a dynamically typed language. The type of a variable in PHP
changes dynamically. This feature is called "type juggling" in PHP)
<?php
$a = 3;
echo gettype($a) . "<br>";
$b = 3.2;
echo gettype($b) . "<br>";

$c = "Hello";
echo gettype($c) . "<br>";

$d = array();
echo gettype($d) . "<br>";

$e = array("red", "green", "blue");


echo gettype($e) . "<br>";

$f = NULL;
echo gettype($f) . "<br>";

$g = false;
echo gettype($g) . "<br>";
?>
output
integer
double
string
array
array
NULL
Boolean

16
The PHP variable handling functions are part of the PHP core. No installation is required to use these functions.
Function Description

boolval() Returns the boolean value of a variable

debug_zval_dump() Dumps a string representation of an internal zend value to output

doubleval() Alias of floatval()

empty() Checks whether a variable is empty

floatval() Returns the float value of a variable

get_defined_vars() Returns all defined variables, as an array

get_resource_type() Returns the type of a resource

gettype() Returns the type of a variable

intval() Returns the integer value of a variable

is_array() Checks whether a variable is an array

is_bool() Checks whether a variable is a boolean

is_callable() Checks whether the contents of a variable can be called as a function

is_countable() Checks whether the contents of a variable is a countable value

is_double() Alias of is_float()

is_float() Checks whether a variable is of type float

is_int() Checks whether a variable is of type integer

is_integer() Alias of is_int()

is_iterable() Checks whether the contents of a variable is an iterable value

is_long() Alias of is_int()

is_null() Checks whether a variable is NULL

is_numeric() Checks whether a variable is a number or a numeric string

is_object() Checks whether a variable is an object

is_real() Alias of is_float()

17
is_resource() Checks whether a variable is a resource

is_scalar() Checks whether a variable is a scalar

is_string() Checks whether a variable is of type string

isset() Checks whether a variable is set (declared and not NULL)

print_r() Prints the information about a variable in a human-readable way

serialize() Converts a storable representation of a value

settype() Converts a variable to a specific type

strval() Returns the string value of a variable

unserialize() Converts serialized data back into actual data

unset() Unsets a variable

var_dump() Dumps information about one or more variables

var_export() Returns structured information (valid PHP code) about a variable

Using Constants
Constants are name or identifier that can't be changed during the execution of the script. In php constants are
define in two ways;
1. Using define() function
2. Using const keyword
In php declare constants follow same rule variable declaration.
 Constant start with letter or underscore only.
 Create a PHP Constant
 Create constant in php by using define() function.
Syntax: define(name, value, case-insensitive)

Name: Specifies the name of the constant


Value: Specifies the value of the constant
Case-insensitive: Specifies whether the constant name should becase-insensitive. Default is false
Example:
<?php
// This creates a case-sensitive constant
define("num",500);
echo num;

// This creates a case-insensitive constant


define("NUM",500,true);
echo num;
18
?>
Output:
500
500

Define constant using const keyword in PHP


The const keyword defines constants at compile time. It is a language construct not a function. It is bit faster
than define(). It is always case sensitive.
Example:
<?php
const Num="500";
echo Num;
?>
Output:
500

Manipulating Variables with Operators


By themselves, variables are simply containers for information. In order to do anything useful with them, you
need operators. Operators are symbols that tell the PHP processor to perform certain actions. For example, the
addition (+) symbol is an operator that tells PHP to add two variables or values, while the greater-than (>)
symbol is an operator that tells PHP to compare two values.
Operators are used to perform operations on variables and values. PHP divides the operators in the
following groups:
1. Arithmetic Operators
2. Logical or Relational Operators
3. Comparison Operators
4. Conditional or Ternary Operators
5. Assignment Operators
6. Array Operators
7. Increment/Decrement Operators
8. String Operators

1.Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition, subtraction,
multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP.
operator Name Syntax Operation
+ Addition $x + $y Sum the operands
– Subtraction $x – $y Differences the operands
* Multiplication $x * $y Product of the operands
/ Division $x / $y The quotient of the operands
** Exponentiation $x ** $y $x raised to the power $y
% Modulus $x % $y The remainder of the operands

Example:
<?php
19
// Define two numbers
$x = 10;
$y = 3;
// Addition
echo "Addition: " . ($x + $y) . "\n";
// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";
// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";
// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";
// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>

Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1++

2.Logical or Relational Operators:


These are basically used to operate with conditional statements and expressions. Conditional statements are
based on conditions. Also, a condition can either be met or cannot be met so the result of a conditional
statement can either be true or false. Here are the logical operators along with their syntax and operations in
PHP.
Operator Name Syntax Operation
And Logical AND $x and $y True if both the operands are true else false
Or Logical OR $x or $y True if either of the operands is true else false
Xor Logical XOR $x xor $y True if either of the operands is true and false if
both are true
&& Logical AND $x && $y True if both the operands are true else false
|| Logical OR $x || $y True if either of the operands is true else false
! Logical NOT !$x True if $x is false
Example:
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";

20
if ($x == 50 or $y == 20)
echo "or Success \n";

if ($x == 50 xor $y == 20)


echo "xor Success \n";

if ($x == 50 && $y == 30)


echo "&& Success \n";

if ($x == 50 || $y == 20)
echo "|| Success \n";

if (!$z)
echo "! Success \n";
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success

3.Comparison Operators:
These operators are used to compare two elements and outputs the result in boolean form. Here are the
comparison operators along with their syntax and operations in PHP.
Operator Name Syntax Operation
== Equal To $x = = $y Returns True if both the operands are equal
!= Not Equal To $x != $y Returns True if both the operands are not equal
<> Not Equal To $x <> $y Returns True if both the operands are unequal
Returns True if both the operands are equal and are
=== Identical $x = = = $y
of the same type
Returns True if both the operands are unequal and
!= = Not Identical $x == $y
are of different types
< Less Than $x < $y Returns True if $x is less than $y
> Greater Than $x > $y Returns True if $x is greater than $y
<= Less Than or Equal To $x <= $y Returns True if $x is less than or equal to $y
>= Greater Than or Equal To $x >= $y Returns True if $x is greater than or equal to $y
Example:
<?php
$a = 80;
$b = 50;
$c = "80";
// Here var_dump function has been used to
// display structured information. We will learn
// about this function in complete details in further
// articles.
21
var_dump($a = = $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a < > $b) + "\n";
var_dump($a = = = $c) + "\n";
var_dump($a != = $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)

4.Conditional or Ternary Operators:


These operators are used to compare two values and take either of the results simultaneously, depending on
whether the outcome is TRUE or FALSE. These are also used as a shorthand notation for if…else statement
that we will read in the article on decision making.
Syntax:
$var = (condition)? value1 : value2;
Here, the condition will either evaluate as true or false. If the condition evaluates to True, then value1 will
be assigned to the variable $var otherwise value2 will be assigned to it.
Operator Name Operation
If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted
otherwise the result is on right.
Example:
<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>
Output:
The number is negative

5.Assignment Operators: These operators are used to assign values to different variables, with or without
mid-operations. Here are the assignment operators along with their syntax and operations, that PHP
provides for the operations.

22
Operator Name Syntax Operation
= Assign $x = $y Operand on the left obtains the value of the
operand on the right
+= Add then Assign $x += $y Simple Addition same as $x = $x + $y
-= Subtract then Assign $x -= $y Simple subtraction same as $x = $x – $y
*= Multiply then Assign $x *= $y Simple product same as $x = $x * $y
/= Divide then Assign (quotient) $x /= $y Simple division same as $x = $x / $y
%= Divide then Assign (remainder) $x %= $y Simple division same as $x = $x % $y

Example
<?php
// Simple assign operator
$y = 75;
echo $y, "\n";
// Add then assign operator
$y = 100;
$y += 200;
echo $y, "\n";
// Subtract then assign operator
$y = 70;
$y -= 10;
echo $y, "\n";
// Multiply then assign operator
$y = 30;
$y *= 20;
echo $y, "\n";
// Divide then assign(quotient) operator
$y = 100;
$y /= 5;
echo $y, "\n";
// Divide then assign(remainder) operator
$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0
6.Array Operators:
These operators are used in the case of arrays. Here are the array operators along with their syntax and
operations, that PHP provides for the array operation.

23
Operator Name Syntax Operation
+ Union $x + $y Union of both i.e., $x and $y

== Equality $x = = $y Returns true if both has same key-value pair

!= Inequality $x != $y Returns True if both are unequal


Returns True if both have the same key-value pair in the
=== Identity $x = = = $y
same order and of the same type
!= = Non-Identity $x != = $y Returns True if both are not identical to each other
<> Inequality $x < > $y Returns True if both are unequal
Example:
<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");
var_dump($x + $y);
var_dump($x = = $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x < > $y) + "\n";
var_dump($x = = = $y) + "\n";
var_dump($x != = $y) + "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

7.Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used to increment or
decrement values.
Operator Name Syntax Operation
++ Pre-Increment ++$x First increments $x by one, then return $x
-- Pre-Decrement --$x First decrements $x by one, then return $x
++ Post-Increment $x++ First returns $x, then increment it by one
-- Post-Decrement $x-- First returns $x, then decrement it by one

24
Example:
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";
$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";
$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
8.String Operators:
This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We
can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the
argument on the left side.
Operator Name Syntax Operation
. Concatenation $x.$y Concatenated $x and $y
Concatenation First concatenates then assigns, same as $x =
.= $x.=$y
and assignment $x.$y
Example: This example describes the string operator in PHP.
<?php
$x = "Vedant";
$y = "BCA";
$z = "College!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output:
VedantBCACollege!!!
VedantBCACollege!!!

25
Difference Between = = and = = = operators
SL
= = Equality = = = Identity
No
Checks if values are equal, ignoring data
1 Checks if both values and data types are identical.
types.
Performs type juggling (automatic
2 No type juggling; data types must match exactly.
conversion) to compare values.
Returns true if values are equal after type Returns true only if both value and data type are
3
juggling. identical.
Example
<?php
Example
$a = 5;
<?php
$b = '5';
$a = 5;
// Strict comparison (===)
$b = '5';
var_dump($a === $b); // bool(false)
4 // Loose comparison (==)
?>
var_dump($a == $b); // bool(true)
?>
Output
Output
bool(false)
bool(true)

Understanding Operator Precedence


Back in math class, you probably learned about BODMAS, a mnemonic that specifies the order in which a
calculator or a computer performs a sequence of mathematical operations: Brackets, Order, Division,
Multiplication, Addition, and Subtraction. Well, PHP follows a similar set of rules when determining which
operators have precedence over others—and learning these rules can save you countless frustrating hours
debugging a calculation that looks right, yet somehow always returns the wrong result!
The following list (a short version of a much longer list in the PHP manual)
illustrates PHP’s most important precedence rules. Operators at the same level have
equal precedence.
● ++ --
●!
●*/%
●+-.
● < <= > >=
● == != === !==
● &&
● ||
● = += -= *= /= .= %= &= |= ^=

Types Of Errors:
Mistake or fault occurs in a program is called error. There are basically 4 types of errors in PHP:
1. Notice
2. Warning
3. Fatal Error
4. Parse Error

26
1. NOTICE
Notice that an error is the same as a warning error i.e. in the notice error does not stop execution of the script.
Notice that the error occurs when you try to access the undefined variable, and then produce a notice
error.
Example
<?php
$a="Uday ";
echo "Notice Error !!";
echo $b;
?>
Output: In the above code we defined a variable which named $a. But we call another variable i.e. $b, which is
not defined. So there will be a notice error produced but execution of the script does not stop, you will see a
message Notice Error !!. Like in the following image:

2. WARNING
Warning errors will not stop execution of the script. The main reason for warning errors are to include a
missing file or using the incorrect number of parameters in a function.
Example
<?php
echo "Warning Error!!";
include ("Welcome.php");
?>
Output: In the above code we include a welcome.php file, however the welcome.php file does not exist in the
directory. So there will be a warning error produced but that does not stop the execution of the script i.e. you
will see a message Warning Error !!.

27
3. FATAL ERROR
Fatal errors are caused when PHP understands what you've written; however what you're asking it to do can't be
done. Fatal errors stop the execution of the script. If you are trying to access
the undefined functions, then the output is a fatal error.
Example
<?php
function fun1(){
echo "Uday Kumar";
}
fun2();
echo "Fatal Error !!";
?>
Output: In the above code we defined a function fun1 but we call another function fun2 i.e. func2 is not
defined. So a fatal error will be produced that stops the execution of the script. Like as in the following image.

4. PARSE ERROR
The parse error occurs if there is a syntax mistake in the script; the output is Parse errors. A parse error
stops the execution of the script. There are many reasons for the occurrence of parse errors in PHP. The
common reasons for parse errors are as follows:
Common reason of syntax errors are:
a. Unclosed quotes
b. Missing or Extra parentheses
c. Unclosed braces
d. Missing semicolon
Example
<?php
echo "C#";
echo "PHP"
echo "C";
?>
Output: In the above code we missed the semicolon in the second line. When that happens there will be a parse
or syntax error which stops execution of the script, as in the following image:

28
Functions In Php:
1. echo statement
In PHP ‘echo’ statement is a language construct and not a function, so it can be used without parenthesis.
But we are allowed to use parenthesis with echo statement when we are using more than one argument with
it.
The end of echo statement is identified by the semi-colon (‘;’). We can use ‘echo’ to output strings or
variables.
Displaying Strings: The keyword echo followed by the string to be displayed within quotes.
<?php

echo "Hello,This is a display string example!";

?>
Output: Hello,This is a display string example!

Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement
instead of single string argument, separating them by comma (‘,’) operator. For example, if we have two strings
say “Hello” and “World” then we can pass them as (“Hello”,”World”).
<?php
echo "Multiple ","argument ","string!";
?>
Output: Multiple argument string!

Displaying Variables: Displaying variables with echo statement is


also as easy as displaying normal strings.
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
echo $text."\n";
echo $num1."+".$num2."=";
echo $num1 + $num2;
?>
Output: Hello, World! 10+20=30

29
The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n” is used for a new
line and is also known as line-break.

2. print statement
The PHP print statement is similar to the echo statement and can be used alternative to echo at many times.
It is also language construct and so we may not use parenthesis: print or print ().
The main difference between the print and echo statement is that print statement can have only one argument
at a time and thus can print a single string. Also, print statement always returns a
value 1.
Like echo, print statement can also be used to print strings and variables.

Displaying String of Text: We can display strings with print statement in the same way we did with echo
statements. The only difference is we cannot display multiple strings separated by comma(,) with a single print
statement. Below example shows how to display strings with the help of PHP print statement:-

<?php
print "Hello, world!";
?>
Output: Hello, world!

Displaying Variables: Displaying variables with print statement is also same as that of echo statement.
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
print $text."\n";

print $num1."+".$num2."=";
print $num1 + $num2;
?>
Output: Hello, World!
10+20=30

3. printf() :Using this function, we can print variables with the help of format specifies.
Example:
<?php
$x=100;
$y=”Vedant”;
printf(“%d”,$x);
printf(“%s”,$y);
?>
Output: 100 Vedant

30
Difference between Echo and Print in PHP

S.No. Echo Statement Print Statement

1 In Echo, we can pass multiple arguments In Print, we cannot pass multiple arguments.
separated by commas.
2 In Echo, we can exhibit the outputs of one or Through the Print statement, we can only show
more strings separated by commas. the strings.
3 Echo can be used with or without parentheses Print can also be used with or without
parentheses.
4 It never returns any value. It always returns the integer value that is 1.

5 This statement is fast as compared to the print It is slow as compared to the echo statement.
statement.

Module 1 Assignment Questions


2 Marks Questions
1.What is PHP?give the Syntax of PHP
2.What are the advantages of PHP and MySQL?
3.Write the simple PHP script to display ‘Hello World’.
4.What is the difference between == and === operators in PHP
5. What is the Purpose of Var_dump() functions.Or Inspecting Variable Contents
6..Define “echo” and “Print” in PHP
7.How to you check the datatype in PHP? Give an example or gettype()
8.What is the purpose of gettype() and unset() functions? Or Setting and Checking Variable Data Types
and Destroying Variables
9. Difference between Global Variable and Local Variables.
10.What is Constant?What is Importants?
11.What is Variable? What is importants?

5 Marks Questions
1.Explain Features of PHP or Advantages of PHP.
2.Explain about datatypes in PHP with an example.
3.Explain about the scope of variable.
4.Explain operators in PHP with example
5.How PHP work?Explain.
6.Write a PHP script that demonstrates the use of comparison and logical operators.include coments to
explain each operation.
7.discuss relational and logical operators in PHP

31

You might also like