0% found this document useful (0 votes)
3 views26 pages

Chapter1-Introduction To PHP

The document provides an introduction to PHP, covering its history, features, installation, and basic syntax. It highlights PHP as a server-side scripting language suitable for web development, detailing its advantages, relationship with HTML, and methods for sending data to web browsers. Additionally, it explains PHP keywords, variables, and the differences between PHP and HTML.

Uploaded by

chethana8182
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)
3 views26 pages

Chapter1-Introduction To PHP

The document provides an introduction to PHP, covering its history, features, installation, and basic syntax. It highlights PHP as a server-side scripting language suitable for web development, detailing its advantages, relationship with HTML, and methods for sending data to web browsers. Additionally, it explains PHP keywords, variables, and the differences between PHP and HTML.

Uploaded by

chethana8182
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/ 26

III BCA (NEP) PHP and MySQL SUMA N | Dept.

of CS

Chapter-1: Introduction to PHP

Introduction to PHP, History and Features of PHP, Installation & Configuration of PHP, Embedding PHP
code in Your Web Pages, Understanding PHP, HTML and White Space, Writing Comments in PHP,
Sending Data to the Web Browser, Data types in PHP, Keywords in PHP, Using Variables, Constants in
PHP, Expressions in PHP, Operators in PHP.

PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the server-side.
PHP is well suited for web development. Therefore, it is used to develop web applications (an application that
executes on the server and generates the dynamic page.).

Some important points need to be noticed about PHP are as followed:


• PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995.
• The acronym used to stand for ‘Personal Home Page’. But, now, PHP is known as Hypertext Preprocessor.
• The most recent version is PHP 8.1.2, launched on 21st Jan 2022.
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP files have extension ".php".
• PHP is an interpreted language, i.e., there is no need for compilation.
• PHP is faster than other scripting languages, for example, ASP and JSP.
• PHP is a server-side scripting language, which is used to manage the dynamic content of the website.

History of PHP
• The first version of PHP is PHP/FI (Form Interpreter) developed by Ramous Lerdorf, monitoring page
view for his online resume.
• This version supports some basic function, capable to handle form data and mSql db.
• PHP/FI 1.0 followed by PHP/FI 2.0 and quickly supplanted in1997 by PHP3.0.
• PHP3.0 developed by Anti Gutmus and Zee Surakshi, complete rewrite of PHP/FI.
• It supports a wide range of database such as MySQL and Oracle.
• In 2003 PHP4.0 was released with better performance, greater reliability, and support for web server other
than Apache. Support OOPs concept.
• PHP 5.0 support message passing, abstract classes, destructor, and better memory management.
• PHP is used on over 15 million website.

Advantages of PHP/PHP Features


• Cross-platform– PHP can efficiently work on different operating systems, like Linux, Windows, and Mac.
• Simple to grasp– Another benefit of this language is that even beginners can quickly adapt to PHP
programming. It is one of the more accessible languages to pick up.
• Open-source– Anyone can use PHP for their web development requirements since the original code has an
open-source nature. Anyone can adapt it and build upon the code further.
• Supportive broad developer community– Get access to PHP’s vibrant online community, with up-to-date
tutorials, documentation, and FAQs available for all developers.
• Multi-database syncing– You can connect this scripting language to different non-rational and rational
databases, like MongoDB, Postgress, and MySQL.
• High-quality performance– PHP operates faster than other scripts like ASP and JSP since it uses a
personalized memory. Therefore, the loading time and workload are relatively shorter.
• Embedded– Developers can embed PHP scripts with HTML scripts and tags.

UCS, Tumkur Page 1


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

• Loosely-typed language– Developers can use a variable without declaring the datatype during scripting and is
automatically used during execution depending on the data type containing the related valuation.
• Syntax familiarity– The syntax of PHP is very simple to understand and is suitable for different web
development needs.
• Error reporting– There are pre-defined error reporting constants available under PHP. It can produce real-
time error warnings, like E_WARNING, E_PARSE, and E_STRICT.
• Better control quality– There is no need for excess or long codes or scripts with PHP. It has higher control on
web solutions; developers can make changes without extra coding.
• High-security– Among the different scripting language types available, PHP is one of the most secure options
with multiple security levels in place. The multi-layered structure safeguards against hacking attempts,
malware, etc.

HTML relationship with PHP


When user wants to write a PHP code, he must know about the HTML without HTML user cannot create the
webpage both HTML and PHP languages are important for web-development. The PHP code is embedded in HTML
files.
Difference between HTML and PHP
HTML PHP
PHP is an open source scripting language used for
HTML is a markup language used to create static
the development of dynamic Websites and dynamic
Webpages.
web applications.
HTML is used for front end development or PHP is used for back end development or
Client side. Server side.
PHP is also easy to learn but not as much as HTML
HTML is very easy to learn with less time it
it takes more time to learn and it won’t accept the
Accepts some small mistakes and gives the output.
mistake in code.

HTML is compatible with almost all Browsers. PHP also compatible with all types of Browsers.

HTML is used to organize the content of the PHP is used to “interact” with the database to
websites. It focuses on how the contents need to retrieve the information, storing the data, e-mail
display with different fonts, size and sending and provides the content to
colors etc. The HTML pages to display on the screen.
<html> <?PHP
<body>

</body>
</html> ?>

Basic PHP Syntax


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.

UCS, Tumkur Page 2


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Below is an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the
text "Hello World!" on a web page:
Example
<?php
echo "Hello World!";
?>
Note: PHP statements end with a semicolon (;).

PHP Echo
PHP echo is a language construct, not a function. Therefore, there is no need to use parenthesis with it. But if more
than one parameter, it is required to use parenthesis. PHP echo statement can be used to print the string, multi-line
strings, escaping characters, variable, array, etc.

The syntax of PHP echo is given below:


void echo ( string $arg1 [, string $... ] )

Example
<?php
echo "Hello by PHP echo";
?>

PHP Print
Like PHP echo, PHP print is a language construct, so no need to use parenthesis with the argument list. Print
statement can be used with or without parentheses: print and print(). Unlike echo, it always returns 1. PHP print
statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc.

The syntax of PHP print is given below:


int print(string $arg)
Example
<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
?>

Difference between echo and print


echo
o echo is a statement, which is used to display the output.
o echo can be used with or without parentheses.
o echo does not return any value.
o We can pass multiple strings separated by comma (,) in echo.
o echo is faster than print statement.

print
o print is also a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than echo statement.

UCS, Tumkur Page 3


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

For Example (Check multiple arguments)


Passing multiple arguments separated by a comma (,) in echo. It will not generate any syntax error.
<?php
$fname = "Gunjan";
$lname = "Garg";
echo "My name is: ".$fname,$lname;
?>

It will generate a syntax error because of multiple arguments in a print statement.


<?php
$fname = "Gunjan";
$lname = "Garg";
print "My name is: ".$fname,$lname;
?>

For Example (Check Return Value)


echo statement does not return any value. It will generate an error if you try to display its return value.
<?php
$lang = "PHP";
$ret = echo $lang." is a web development language.";
echo "</br>";
echo "Value return by print statement: ".$ret;
?>

print returns a value, which is always 1.


<?php
$lang = "PHP";
$ret = print $lang." is a web development language.";
print "</br>";
print "Value return by print statement: ".$ret;
?>

PHP Case Sensitivity


In PHP, 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 equal and legal:
Example
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
Note: However; all variable names are case-sensitive!
In the example below; only the first statement will display the value of the $color variable! This is
because $color, $COLOR, and $coLOR are treated as three different variables:
Example
<?php
$color = "red";

UCS, Tumkur Page 4


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

echo "My car is " . $color . "<br>";


echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

Installation & Configuration of PHP


PHP is a popular backend programming language. PHP programs can be written on any editor, such as - Notepad,
Notepad++, Dreamweaver, etc. These programs save with .php extension, i.e., filename.php inside the htdocs folder.
For example - p1.php.
Install XAMPP/WAMPP/LAMPP software. Those were installed XAMPP tool in C Drive, then the path for the
htdocs directory will be "C:\xampp\htdocs". PHP program runs on a web browser such as - Chrome, Internet
Explorer, Firefox, etc. Below some steps are given to run the PHP programs.
Step 1: Create a simple PHP program like hello world.
<?php
echo "Hello World!";
?>
Step 2: Save the file with p1.php name in the htdocs folder, which resides inside the xampp folder.
Note: PHP program must be saved in the htdocs folder, which resides inside the xampp folder, where you installed the
XAMPP. Otherwise it will generate an error - Object not found.
Step 3: Run the XAMPP server and start the Apache and MySQL.
Step 4: Now, open the web browser and type localhost http://localhost/hello.php on your browser window.
Step 5: The output for the above p1.php program will be shown as the screenshot below:

Embedding PHP code in Your Web Pages


The steps to Embedding PHP code in Your Web Pages are:
1. Open an HTML file in a text editor
2. Place the cursor in any tag of the <body> tag where you want to add the PHP code
3. Type the PHP start tag <?php and the PHP end tag ?>
4. Type the PHP code between the tags
5. Save the HTML file and run it in a browser
The code wrapped between the start and end tags are considered to be PHP code and will be executed on the
server side before the requested file is sent to the client browser. Although it is not necessary to include spaces
between the markers and the enclosed text, doing so improves readability.

Understanding PHP
PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL
database.
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.

UCS, Tumkur Page 5


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

o It can access cookies variable and also set cookies.


o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.
o Using PHP language, you can control the user to access some pages of your website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best language to learn.
o PHP can handle the forms, such as - collect the data from users using forms save it into the database, and
return useful information to the user. For example - Registration form.

HTML and White Space


• By Using &nbsp semicolon to add more than one whitespace between words or characters in a string.
• By Using ctype_space() function in PHP to check for whitespace characters. It returns TRUE if every character
in text creates some sort of white space, FALSE otherwise. This includes the blank character, as well as tabs,
vertical tabs, line feeds, carriage returns, and form feeds.

Comments in PHP
PHP comments can be used to describe any line of code so that other developer can understand the code easily. It
can also be used to hide any code.
PHP supports single line and multi-line comments. These comments are similar to C/C++ and Perl style (UNIX shell
style) comments.

PHP Single Line Comments


There are two ways to use single line comments in PHP.
o // (C++ style single line comment)
o # (Unix Shell style single line comment)
Example
<?php
// this is C++ style single line comment
# this is Unix Shell style single line comment
echo "Welcome to PHP single line comments";
?>

PHP Multi Line Comments


In PHP, we can comments multiple lines also. To do so, all lines enclose within /* */.
Example
<?php
/*
Anything placed
within comment
will not be displayed
on the browser;
*/
echo "Welcome to PHP multi line comment";
?>

Sending Data to the Web Browser


PHP has two methods for sending information to a web server from a browser client: GET and POST. The GET
method adds encoded user information to the page request, while the POST method transfers information via
HTTP headers.

UCS, Tumkur Page 6


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

The GET method is limited to 1024 characters and is used to submit HTML form data. The information is collected
by the predefined $_GET variable and is visible to everyone in the browser's address bar. The page and the
encoded information are separated by the ? character.
The POST method does not have any restriction on data size to be sent. Before the browser sends the information,
it encodes it using a scheme called URL encoding. The data submitted by this method is collected by the
predefined $_POST variable instead of $_GET. The encoded information is embedded in the body of the HTTP
request, so the data is not visible in the page URL.

Keywords in PHP
PHP keywords are words that have meaning and are automatically understood by PHP. They are fundamental
building blocks that help developers write efficient, maintainable, and powerful code. PHP keywords cannot be
used as variable names, class names, method names, or constants.
PHP Keywords
__halt_compiler() abstract and array() as

break callable case catch class

clone const continue declare default

die() do echo else elseif

empty() enddeclare endfor endforeach endif

endswitch endwhile eval() exit() extends

final finally fn (as of PHP 7.4) for foreach

function global goto if implements

include include_once instanceof insteadof interface

isset() list() match (as of PHP 8.0) namespace new

or print private protected public

readonly (as of PHP 8.1.0) * require require_once return static

switch throw trait try unset()

use var while xor yield

yield from

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
• As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically
analyzes the values and makes conversions to its correct datatype.
• After declaring a variable, it can be reused throughout the code.
• Assignment Operator (=) is used to assign the value to a variable.

Rules for PHP Variables:


• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character

UCS, Tumkur Page 7


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

• A variable name cannot start with a number


• A PHP variable name cannot contain spaces.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)

Syntax of declaring a variable in PHP is given below:


$variablename=value;

PHP Variable: Declaring string, integer, and float


Below is the example to store string, integer, and float values in PHP variables.

File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static

Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
Example
Variable with global scope:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>

Output:
Variable x inside function is:
Variable x outside function is: 5

UCS, Tumkur Page 8


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Local Scope
The variables that are declared within a function are called local variables for that function. These local variables
have their scope only in that particular function in which they are declared. This means that these variables cannot
be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the variable declared
inside the function.
Example
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>

Output:
Variable x inside function is: 5
Variable x outside function is:

Static Variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we
need to store a variable even after completion of function execution. Therefore, another important feature of
variable scoping is static variable. We use the static keyword before the variable to define a variable, and this
variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program execution leaves the
scope.
Example:
File: static_variable.php
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
//first function call
static_var();
//second function call
static_var();
?>

UCS, Tumkur Page 9


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
Notice that $num1 regularly increments after each function call, whereas $num2 does not. This is why because
$num1 is not a static variable, so it freed its memory after the execution of each function call.

PHP Global Variables - Superglobals


Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of
scope - and it can access from any function, class or file without having to do anything special.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION

1. PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script
(also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS [index]. The index holds the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from outside the
function!

2. PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];

UCS, Tumkur Page 10


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside $_SERVER:
Element/Code Description

$_SERVER['PHP_SELF'] Returns the filename of the currently executing script

$_SERVER['SERVER_NAME'] Returns the name of the host server (such as www.w3schools.com)

$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable because not
all user-agents support it)

$_SERVER['SCRIPT_NAME'] Returns the path of the current script

$_SERVER['HTTP_HOST'] Returns the Host header from the current request

3. $_REQUEST: It is used to collect the data after submitting a html form. It is not widely used.$_GET and $_POST
perform the same task.
4. $_GET: It is a default form request. The data passed through get request is visible on the URL browser, so it is
notsecured. We can get limited amount of data through get request.
5. $_POST: Post request is widely used to submit form that have large amount of data such as file upload, image
upload etc. The data passed through post request is not visible on URL so it is secured. We can send large
amount of data through this.
6. $_SESSION: It is a way to store the information to be used at the multiple pages. By default, session variables
will be lost after closes the browser. Session_start() must be the very first in the document before any HTML
tags.
7. $_COOKIE: Cookies are small text files loaded from a server to a client computer. It stores the information
regarding the client computer so that the same page is visited by the user again and again. It decreases the
latency period to open the page.
8. $_FILES: It is used to upload the files. It is associated with 2-D array and it keeps all the information related to
the uploadedfile.
9. $_ENV: it is a super global variable that contains the environment variable where that environment variable is
provided by the shell under which php is running.

Data Types in PHP


PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be
categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types

UCS, Tumkur Page 11


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

PHP Data Types: Scalar Types


It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object

PHP Data Types: Special Types


There are 2 special data types in PHP.
1. resource
2. NULL

PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often
used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>

PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without
fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or
decimal point, including a negative or positive sign.

UCS, Tumkur Page 12


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To
clarify this, see the example below:
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>

PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>

PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly
declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>

UCS, Tumkur Page 13


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to
external PHP resources. For example - a database call. It is an external resource.

PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is
case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>

Automatic Type Conversion & Forcing a Type with Type Casting


The meaning of type casting is to use the value of a variable with different data type. In other word typecasting is a
way to utilize one data type variable into the different data type. Typecasting is the explicit conversion of data type
because user explicitly defines the data type in which he wants to cast.
PHP does not require or support type definition of the variable. In PHP we never define data type while declaring
the variable. In PHP variables automatically decide the data type on the basis of the value assignment or context.
There are two types of casting
• Implicit Casting (Automatic)
• Explicit Casting (Manual)

Implicit Casting
Implicit casting is something done by PHP according to your code, but you are not capable of customizing. When
dividing an integer by another integer the result can either be integer or float. The decision is taken by PHP. See the
below example.
PHP Implicit Casting Example
<?php
$x = 2;
$y = 4;
var_dump($x / $y); // 2/4 = 0.5 (Float)
var_dump($y / $x); // 4/2 = 2 (Int)

Explicit Casting
We can explicitly cast a variable to different data types. For instance, we can convert a float to an integer like
following. (The decimal portion will be dropped)
PHP Explicit Casting - Float to Integer
<?php
$x = 5.35;
$y = (int) $x; // cast $x to integer
var_dump($y);
The data type you need to change the variable into should be written inside parentheses, before the variable.

UCS, Tumkur Page 14


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

The following casts are allowed:

Cast Description
(int) or (integer) Cast to an integer.

(float) or (double) or (real) Cast to a float.

(bool) or (boolean) Cast to a boolean.

(string) Cast to a string.

(array) Cast to an array.

(object) Cast to an object.

Explicit Casting Examples


1. Casting to an integer
Both (int) and (integer) casts are valid.
When casting a float to integer, the decimal portion will be dropped. So, make sure that this drop does not affect
any other things.

PHP Explicit Casting - Float to Integer


<?php
$x = 5.35;
$y = (int) $x; // cast $x to integer
var_dump($y);

PHP Explicit Casting - String to Integer


<?php
$x = '25';
$y = (integer) $x; // cast $x to int
var_dump($y);

The following example shows a useful way that you can use casting for. Casting any string that starts with a
number followed by a phrase to an integer will return the starting number as an integer.

PHP Explicit Casting - Phrase to Integer


<?php
$string = '10 Animals';
$numberOfAnimals = (int) $string;
echo $numberOfAnimals;

UCS, Tumkur Page 15


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

2. Casting to a float
(float) , (double) and (real) are valid casts. All of them casts the variable to float data type.
When casting an integer to float there won't be any data loss, as integers do not have any decimal portion.
PHP Explicit Casting - Integer to Float
<?php
$x = 7;
$y = (float) $x; // $y is 7, but float
var_dump($y);

3. Casting to a boolean
Both bool and boolean are valid.
PHP Explicit Casting to Boolean
<?php
$a = (bool) 0;
$b = (bool) 5;
$c = (bool) '';
$d = (bool) 'Hyvor';
$e = (bool) [];
$f = (bool) [2,5];
$g = (bool) null;
var_dump($a); // false
var_dump($b); // true
var_dump($c); // false
var_dump($d); // true
var_dump($e); // false
var_dump($f); // true
var_dump($g); // false
$h = (boolean) 'Hyvor'; // boolean also valid
var_dump($h); // true

4. Casting to an array
We can add any single variable into an array which has only one element.
PHP Explicit Casting to Array
<?php
$a = (array) 5;
$b = (array) 'Hyvor';
$c = (array) true;

UCS, Tumkur Page 16


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

var_dump($a); // [5]
var_dump($b); // ['Hyvor']
var_dump($c); // [true]

Non-Decimal Number Systems


The most numbers in PHP are entered in using decimal (base 10), you may also specify themin hexadecimal (base
16) or octal (base 8).

Octal Number System:


To represent a octal number system in PHP by using to initialize a variable with 06 followed by a number you
want to represent in octal.
Example:

Output:
3291

Hexadecimal Number System:


To represent a Hexadecimal number system in PHP by using to initialize a variable with 0X followed by a
number you want to represent in hexadecimal.
Example:

Output:
68

Pre-Set Variables
PHP has set a number of variables for you containing information about the server, the environment, and the
request from your visitor. These are stored in the super global arrays for you, and you can get a fairly complete list
of what is available by using the phpinfo() output.
The most commonly used variables, all of which are stored in the $_SERVER super global, are as follows:
Name Value
REQUEST_METHOD Either GET or POST
PHP_SELF The name of the current script
PATH_INFO Any data passed in the URL after the script name
HTTP_REFERER If the user clicked a link to get the current page, this will contain the
URL of the previous page they were at, or it will be empty if the user
entered the URL directly.
HTTP_USER_AGENT The name reported by the visitor's browser
QUERY_STRING Includes everything after the question mark in a GET request

UCS, Tumkur Page 17


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Constants
PHP constants are name or identifier that can't be changed during the execution of the script except for magic
constants, which are not really constants. PHP constants can be defined by 2 ways:
1. Using define() function
2. Using const keyword

Constants are similar to the variable except once they defined, they can never be undefined or changed. They
remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can
be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.


Note: Unlike variables, constants are automatically global throughout the script.

PHP constant: define()


Use the define() function to create a constant. It defines constant at run time. The syntax of define() function in
PHP.
define(name, value, case-insensitive)
1. name: It specifies the constant name.
2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case
sensitive by default.

Example to PHP constant using define().


File: constant1.php
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>

Create a constant with case-insensitive name:


File: constant2.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
echo MESSAGE, "</br>";
echo message;
?>
File: constant3.php
<?php
define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
echo MESSAGE;
echo message;
?>

PHP constant: const keyword


PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a
language construct, not a function. The constant defined using const keyword are case-sensitive.
File: constant4.php
<?php

UCS, Tumkur Page 18


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

const MESSAGE="Hello const by JavaTpoint PHP";


echo MESSAGE;
?>

Constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.
Syntax
The syntax for the following constant function:
constant (name)
File: constant5.php
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>

Pre-Set Constants
Pre-set Constants are reserved constants. Some constant names are reserved by PHP andcannot be redefined.
I we redefine these constants in your PHP program then, Notice will be issued By the Interpreter.
Some of the pre-defined constants of PHP are:
M_PI , M_SQRT2 , M_LOG2E , NAN , false , true , M_E , INF , M_PI_2 , M_LOG2E , M_LN10 etc.,

Expressions in PHP
An expression is a combination of values, variables, operators, and function calls that can be evaluated to produce a
value.
In PHP, an expression is a combination of values, variables, operators, and function calls that can be evaluated to
produce a single value. These elements come together to form a logical operation, and the result of this operation is
the output of the expression.
Components of an Expression:
1. Values: These are the raw data elements in programming. Examples include numbers (3, 10.2), strings (‘Hello
World'), and booleans (true, false).
2. Variables: Variables are containers for holding values. They have names and can store different values at
different points in program’s execution.
3. Operators: Operators are symbols or keywords that perform operations on values and variables. Examples
include arithmetic operators (+, -, * /), comparison operators (==, !=, <, >) and logical operators (&&, || ).
4. Function Calls: Functions are reusable blocks of code that perform specific tasks. When you call a function, it
can return a value. Function calls typically involve passing arguments enclosed in parentheses.

Examples of Expressions
1. Arithmetic Expression:
$result = 5 + 3;
Here, the expression 5+3 adds the values 5and 3, resulting in the value 8.
2. String Concatenation Expression:
$name = 'John';
$greetings = 'Hello, ' . $name;
The expression "Hello, " . $name concatenates the string "Hello, " with the value store in the variable $name .

UCS, Tumkur Page 19


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

3. Function Call Expression:


$length = strlen('Hello');
The expression calls the strlen function to get the length of the string 'Hello' , producing the value 5 .
4. Comparison Expression:
$age = 30;
$isAdult = $age >= 18;
The expression $age >= 18 evaluates to true or false based on whether the value of $age is greater than or equal
to 18.
5. Ternary Operator Expression:
$number = 7;
$isEven = ($number % 2 == 0) ? true : false;
The expression uses the ternary operator to determine if. $number is even, producing true or false accordingly.

Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:


o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

Unary Operators: Incrementing/Decrementing Operators


The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation

++$a Increment the value of $a by one, then return $a


++ Increment
$a++ Return $a, then increment the value of $a by one

--$a Decrement the value of $a by one, then return $a


-- decrement
$a-- Return $a, then decrement the value of $a by one

UCS, Tumkur Page 20


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction,
etc. with numeric values.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.

Operator Name Example Explanation

And And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true

Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

UCS, Tumkur Page 21


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b

*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b

/= Divide then Assign $a /= $b Find quotient same as $a = $a / $b


(quotient)

%= Divide then Assign $a %= $b Find remainder same as $a = $a % $b


(remainder)

Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.

| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1

^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.

~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1

<< Shift left $a << $b Left shift the bits of operand $a $b steps

>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places

Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:

Operator Name Example Explanation

== Equal $a == $b Return TRUE if $a is equal to $b

=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type

Return TRUE if $a is not equal to $b, and they are not of same
!== Not identical $a !== $b
data type

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

UCS, Tumkur Page 22


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

> Greater than $a > $b Return TRUE if $a is greater than $b

<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b

Greater than or equal


>= $a >= $b Return TRUE if $a is greater than or equal $b
to

Return -1 if $a is less than $b


<=> Spaceship $a <=>$b Return 0 if $a is equal $b
Return 1 if $a is greater than $b

String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP, which
are given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign the


Assignment concatenated string to $a, e.g. $a = $a . $b

Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of arrays.

Operator Name Example Explanation

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same key/value pair

!= Inequality $a != $b Return TRUE if $a is not equal to $b

=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same
type in same order

!== Non-Identity $a !== $b Return TRUE if $a is not identical to $b

<> Inequality $a <> $b Return TRUE if $a is not equal to $b

Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on conditions:

UCS, Tumkur Page 23


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE

?? Null $x = expr1 ?? expr2 Returns the value of $x.


coalescing The value of $x is expr1 if expr1 exists, and is
not NULL.
If expr1 does not exist, or is NULL, the value of
$x is expr2.
Introduced in PHP 7

The Scope Resolution Operator

In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access
constants, properties and methods defined at class level. When referring to these items outside class definition,
name of class is used along with scope resolution operator. This operator is also called Paamayim Nekudotayim,
which in Hebrew means double colon.

<?php
class A{
const PI=3.142;
static $x=10;
}
echo A::PI;
echo A::$x;
$var='A';
echo $var::PI;
echo $var::$x;
?>

Inside class
To access class level items inside any method, keyword - self is used
<?php
class A{
const PI=3.142;
static $x=10;
static function show(){
echo self::PI . self::$x;
}
}
A::show();
?>

UCS, Tumkur Page 24


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

In child class
If a parent class method overridden by a child class and you need to call the corresponding parent method, it must
be prefixed with parent keyword and scope resolution operator
<?php
class testclass{
public function sayhello(){
echo "Hello World";
} }
class myclass extends testclass{
public function sayhello(){
parent::sayhello();
echo "Hello PHP";
} }
$obj=new myclass();
$obj->sayhello();
?>

Regular Expression or Pattern Matching in PHP


Regular Expression or Pattern Matching is powerful pattern matching algorithm that can be performed in a single
expression. Regular expressions are commonly known as regex. These are nothing more than a pattern or a
sequence of characters, which describe a special search pattern as text string. It is used to search a specific pattern
in a given string. It helps to validating e-mail address, if adding domain names, telephone numbers etc. Php has
built-in functions that allow us to work with regular expressions.

Regular Expression Functions


PHP provides a variety of functions that allow you to use regular expressions. The preg_match(), preg_match_all()
and preg_replace() functions are some of the most commonly used ones:

UCS, Tumkur Page 25


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

var_dump() function: The var_dump() function in PHP displays information about one or more variables,
including their type and value. The syntax for var_dump() is void var_dump ($expsn), where $expsn is a single-
argument function that accepts a single variable or an expression containing several space separated variables of
any type. The function returns no value.
• Example 1: var_dump(var_dump(2, 2.1, TRUE, array(1, 2, 3, 4)));
• Example 2: $a = array(1, 2, array(``a'', ``b'', ``c'')); var_dump($a);`
• Example 3: $a = 32; echo var_dump($a) ;
• $b = ``Hello world! ''; echo var_dump($b) ;
• $c = 32.5; echo var_dump($c) ;
The var_dump() function explores arrays and objects recursively, with values indented to show structure. It is
available in PHP 4.0 and later.

************************

UCS, Tumkur Page 26

You might also like