0% found this document useful (0 votes)
25 views

UNIT 1-WT-PHP-IIB.COM(CA)

Uploaded by

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

UNIT 1-WT-PHP-IIB.COM(CA)

Uploaded by

gansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

SEMESTER III UNIT I

WEB TECHNOLOGY(PHP)

UNIT- I
Introduction to PHP – Basic Development concepts-Creating First PHP scripts – Using
Variables and Operators- Storing data in Variable –Understanding data types- Setting and
Checking Variables Data types-Using Constants-Manipulating Variables with operators

Introduction to 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.).

PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
7.4.0 is the latest version of PHP, which was released on 28 November. Some important
points need to be noticed about PHP are as followed:

o PHP stands for Hypertext Preprocessor.


o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content
of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

use 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.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 1


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

PHP Features

performance:

PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.

Open Source:

PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.

Web Development

PHP is widely used in web development nowadays. PHP can develop dynamic websites
easily. But you must have the basic the knowledge of following technologies for web
development as well.

o HTML
o CSS
o JavaScript
o Ajax
o XML and JSON
o jQuery

Prerequisite

Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript.
So, learn these technologies for better implementation of PHP.

HTML - HTML is used to design static webpage.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 2


CSS - CSS helps to make the webpage content more effective and attractive.

JavaScript - JavaScript is used to design an interactive website.

A PHP file contains HTML tags and some PHP scripting code. It is very easy to create a
simple PHP example.
Create a file and write HTML tags + PHP code

save this file with .php extension.


Example:1

1. <?php
2. //your code here
3. ?>

Save file name: File: first.php

1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello First PHP</h2>";
6. ?>
7. </body>
8. </html>

Output:

Hello First PHP

Example:2
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "Hello world using echo </br>";
6. ECHO "Hello world using ECHO </br>";
7. EcHo "Hello world using EcHo </br>";
8. ?>
9. </body>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 3


10. </html>
Output:
Hello world using echo
Hello world using ECHO
Hello world using EcHo
PHP Echo

PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis
with it. But if you want to use more than one parameter, it is required to use parenthesis.

The syntax of PHP echo is given below:

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


PHP echo statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:

o echo is a statement, which is used to display the output.


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

Example:1

1. <?php
2. echo "Hello by PHP echo";
3. ?>
Output:
Hello by PHP echo

Example:2
1. <?php
2. $msg="Hello JavaTpoint PHP";
3. echo "Message is: $msg";
4. ?>

Output:
Message is: Hello JavaTpoint PHP

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 4


PHP-Basic Development Concepts
When developing a PHP application for Web, the typical approach is to embed PHP code into
one or more standard HTML documents using special “tags”, or delimiters.
<html>
<head></head>
<body>
<div>
<?php echo "Welcome to PHP Gurukul"; ?>
</div>
</body>
</html>

When such an HTML documents is requested by user, a PHP aware Web server can
recognize and execute the PHP code blocks and interpolate the resulting output into the
HTML documents before returning it to the requesting user. The result: a Web page or
application that almost seems alive, responding intelligently to user actions by virtue of PHP
program logic embedded within it. Fig 1-1 illustrates the process, showing the four elements
of the LAMP framework, described later in this section Here’s what’s happening in fig1-1:
1. Joe pops open his Web browser at home and types in the URL to a Web site. After
looking up domain, Joe’s browser(the client) sends an HTTP request to the
corresponding server IP address.
2. The Web server handling HTTP request for the domain receives the request and notes
that URL end with a .php suffix. Because the server is programmed to automatically
redirect all such requests to the PHP layer, it simply invokes the PHP interpreter and
passes it the contents of the named file.
3. The PHP interpreter parses the file, executing the code in the special PHP tags. Within
these tags, you can perform calculations, process user input, interact with a database,
read and writes files… the list goes on! Once the script interpreter has completed
executing the PHP instructions, it returns the result to the browser, clean up after itself,
and goes back into hibernation.
4. The results retuned by the interpreter are transmitted to Joe’s browser by the Web server.
From the preceding explanation, it should be clear that to get started building PHP
applications, your development environment must contains 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.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 5


 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 components
 A database engine(such as MySQL) that hold application data, accepts connections from
the PHP layer, and modifies or retrieves data from 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 Java Scripts.]]>
Creating First PHP scripts

First PHP Script

To get started, you'll need a text editor to write your PHP code. You can use any text editor
you prefer, such as Notepad++, Sublime Text, or Visual Studio Code. Once you have your
text editor set up, follow the steps below to create your first PHP script:

1. Step 1: Create a new PHP file

Start by creating a new file with a .php extension, such as "first_script.php". This
extension is necessary to indicate that the file contains PHP code.

2. Step 2: Opening and closing PHP tags

In PHP, you need to enclose your code within opening and closing PHP tags. These
tags allow the PHP interpreter to identify and execute the PHP code within them.
Open your PHP file and add the following tags:

<?php
//your code here
?>

3.Step 3: Writing your first PHP script

Now you can start writing your PHP script within the PHP tags. Here's an example of
a simple PHP script that prints "Hello, World!" to the browser:

<?php
echo "Hello by PHP echo";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 6


?>

In this script, the echo statement is used to output the string "Hello, World!" to the
browser. The semicolon (;) at the end of the line indicates the end of the statement.

Step 4: Running your PHP script

To run your PHP script, you'll need a web server with PHP installed. You can either install a
local server like XAMPP or WAMP on your computer or use an online development
environment like Replit or PHPFiddle.

If you're using a local server, make sure to place your PHP file in the appropriate directory,
typically the "htdocs" folder for XAMPP or the "www" folder for WAMP. Then, access your
script through the browser by entering the server's URL followed by the name of your PHP
file (e.g., http://localhost/first_script.php).

Comments in PHP

A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced coming back
to their own work a year or two later and having to re-figure out what they did.
Comments can remind you of what you were thinking when you wrote the code
 Leave out some parts of your code

Syntax for comments in PHP code:

// This is a single-line comment

# This is also a single-line comment

/* This is a

multi-line comment */

single Line Comments

Single line comments start with //.

Any text between // and the end of the line will be ignored (will not be executed).

Also use # for single line comments,

Example:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 7


<body>
<?php
// Outputs a welcome message:
echo "Welcome Home!";
?>
</body>
</html>

Output:

Welcome Home

PHP Multiline Comment


Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

<!DOCTYPE html>
<html>
<body>
<?php
/*
The next statement will
print a welcome message
*/
echo "Welcome Home!";
?>
</body>
</html>
Output:
Welcome Home!

PHP Variables

A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 8


 Variable names are case-sensitive ($age and $AGE are two different variables)

Example:

<!DOCTYPE html>
<html>
<body>
<?php
$txt = "how are you";
echo "Hai $txt!";
?>
</body>
</html>

Output:

Hai how are you

Example:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>

Output:

PHP is a Loosely Typed Language

PHP automatically associates a data type to the variable, depending on its value

Variable Types

PHP has no command for declaring a variable, and the data type depends on the value of the
variable

!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // $x is an integer
$y = "John"; // $y is a string

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 9


echo $x;
echo $y;
?>
</body>
</html>

Output:

5john

Get the Type

To get the data type of a variable, use the var_dump() function.

Example

The var_dump() function returns the data type and the value:

!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
var_dump($x);
?>
</body>
</html>
Output:
int(5)

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:

<!DOCTYPE html>
<html>
<body>
<?php
$x = "John";
echo $x;
?>
</body>
</html>
Output:
John

Assign Multiple Values

You can assign the same value to multiple variables in one line:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 10


!DOCTYPE html>
<html>
<body>
<?php
$x = $y = $z = "Fruit";
echo $x;
echo $y;
echo $z;
?>
</body>
</html>
Output:
FruitFruitFruit
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators

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

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided


by $y

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 11


** Exponentiation $x ** $y Result of raising $x to the
$y'th power

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.

Assignment Same as... Description

x=y x=y The left operand gets set to the value of the
expression on the right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 12


operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they


are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they
are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to


equal to $y

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 13


<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, depending on if $x is less
than, equal to, or greater than $y.
Introduced in PHP 7.

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 14


or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1


assignment

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 15


+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same


key/value pairs in the same order and of the
same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators

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

Operator Name Example Result

?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.


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

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 16


?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
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

Storing data in Variable

Use the variable name on the left side of an assignment statement.

Example sets the value of the variable alpha . The value generated on the right side of the
assignment statement is stored in the variable.

To store a value in a variable

 Use the variable name on the left side of an assignment statement.

The following example sets the value of the variable alpha.

alpha = (beta * 6.27) / (gamma + 2.1)

The value generated on the right side of the assignment statement is stored in the
variable.

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:

<!DOCTYPE html>
<html>
<body>
<?php
$x = "John";
echo $x;
?>
</body>
</html>

OUTPUT

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 17


John

Assign Multiple Values

You can assign the same value to multiple variables in one line:

<!DOCTYPE html>
<html>
<body>
<?php
$x = $y = $z = "Fruit";
echo $x;
echo $y;
echo $z;
?>
</body>
</html>
OUTPUT
FruitFruitFruit

Understanding Data types

Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

PHP String

A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

<!DOCTYPE html>
<html>
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 18


var_dump($y);
?>
</body>
</html>

Output:

string(12) "Hello world!"


string(12) "Hello world!"

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

Rules for integers:

 An integer must have at least one digit


 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8),
or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
Output:
int(5985)

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10.365;
var_dump($x);

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 19


?>
</body>
</html>
Output:
float(10.365)

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

<!DOCTYPE html>
<html>
<body>
<?php
$x = true;
var_dump($x);
?>
</body>
</html>
Output:
bool(true)

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
Output:

[0]=> string(5) "Volvo"


[1]=> string(3) "BMW"
[2]=> string(6) "Toyota"

PHP Object

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.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 20


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.

Let's assume we have a class named Car that can have properties like model, color, etc. We
can define variables like $model, $color, and so on, to hold the values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) 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.

<!DOCTYPE html>
<html>
<body>

<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("red", "Volvo");


var_dump($myCar);
?>

</body>
</html>
Output:
object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }

PHP NULL Value

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:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 21


<html>
<body>

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
</body>
</html>
Output:
NULL

Change Data Type

If you assign an integer value to a variable, the type will automatically be an integer.

If you assign a string to the same variable, the type will change to a string:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
var_dump($x);

echo "<br>";

$x = "Hello";
var_dump($x);
?>

<p>Line breaks were added for better readability.</p>

</body>
</html>
Output:

int(5)
string(5) "Hello"

Line breaks were added for better readability.

PHP Resource

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.

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 22


We will not talk about the resource type here, since it is an advanced topic.

Setting and Checking variables Data types

Setting Variable Data Types:

1. Declare: Use the declare statement to set the data type of a variable.

declare(strict_types=1); // Enable strict typing


$x = 5; // Integer
$y = 'hello'; // String

1. Type Casting: Use casting operators to convert a value to a specific type.

$x = (int) '5'; // Cast string to integer


$y = (bool) 'true'; // Cast string to boolean

1. Assignment: Assign a value of a specific type to a variable.

$x = 5; // Integer
$y = 'hello'; // String

Checking Variable Data Types:

1. gettype(): Returns the type of a variable.

$x = 5;
echo gettype($x); // Outputs: "integer"

1. is_type(): Check if a variable is of a specific type.

$x = 5;
if (is_int($x)) { echo "x is an integer"; }

1. var_dump(): Displays detailed information about a variable, including its type.

$x = 5;
var_dump($x); // Outputs: "int(5)"

Some commonly used type-checking functions in PHP include:

- is_int()
- is_float()
- is_string()
- is_bool()
- is_array()
- is_object()
- is_null()

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 23


- is_resource()
- is_callable()
- is_iterable()

By setting and checking variable data types, you can ensure that your code is working with
the correct data types, which can help prevent errors and improve code reliability.

1. is_int(): Check if a value is an integer.


2. is_float(): Check if a value is a floating-point number.
3. is_string(): Check if a value is a string.
4. is_bool(): Check if a value is a boolean (true or false).
5. is_array(): Check if a value is an array.
6. is_object(): Check if a value is an object.
7. is_null(): Check if a value is null.
8. is_resource(): Check if a value is a resource (such as a file or database handle).
9. is_callable(): Check if a value is a callable function or method.
10. is_iterable(): Check if a value is an iterable (such as an array or object that can be looped
through with foreach).

These functions are useful for validating user input, checking the type of a variable, and
ensuring that your code is working with the correct data types.

Here are some examples of how to use these functions:

- if (is_int($x)) { echo "x is an integer"; }


- if (is_string($y)) { echo "y is a string"; }
- if (is_array($z)) { echo "z is an array"; }

Using Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

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

Create a PHP Constant

To create a constant, use the define() function

Syntax
define(name, value, case-insensitive);

Parameters:+

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 24


 name: Specifies the name of the constant
 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false. Note: Defining case-insensitive constants was deprecated in PHP 7.3.
PHP 8.0 accepts only false, the value true will produce a warning.
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 // case-sensitive constant name
 define("GREETING", "Welcome to W3Schools.com!");
 echo GREETING;
 ?>

 </body>
 </html>

Output:

Welcome to W3Schools.com!

HP const Keyword

You can also create a constant by using the const keyword.

Example

Create a constant with the const keyword:

<!DOCTYPE html>
<html>
<body>
<?php
const MYCAR = "Volvo";
echo MYCAR;
?>
</body>
</html>
Output:
Volvo

PHP Constant Arrays

Create an Array constant using the define() function.

Example

Create an Array constant:

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 25


<!DOCTYPE html>
<html>
<body>

<?php
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];
?>

</body>
</html>
Output:
Alfa Romeo

Constants are Global

Constants are automatically global and can be used across the entire script.

Example

This example uses a constant inside a function, even if it is defined outside the function:

<!DOCTYPE html>
<html>
<body>

<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING;
}

myTest();
?>

</body>
</html>

Ouput:
Welcome to W3Schools.com!

Manipulating Variables with Operators.


Arithmetic Operators

- $x = 5 + 3; (Addition) - $x is now 8

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 26


- $x = 5 - 3; (Subtraction) - $x is now 2
- $x = 5 * 3; (Multiplication) - $x is now 15
- $x = 5 / 3; (Division) - $x is now 1.67
- $x = 5 % 3; (Modulus) - $x is now 2
- $x = 5 ** 3; (Exponentiation) - $x is now 125

Assignment Operators

- $x = 5; (Assignment) - $x is now 5
- $x += 3; (Addition and Assignment) - $x is now 8
- $x -= 3; (Subtraction and Assignment) - $x is now 2
- $x *= 3; (Multiplication and Assignment) - $x is now 15
- $x /= 3; (Division and Assignment) - $x is now 1.67
- $x %= 3; (Modulus and Assignment) - $x is now 2
- $x **= 3; (Exponentiation and Assignment) - $x is now 125

Comparison Operators

- if ($x == 5) { echo "x is 5"; } (Equal) - Outputs: "x is 5"


- if ($x != 5) { echo "x is not 5"; } (Not Equal) - Outputs: "x is not 5"
- if ($x > 5) { echo "x is greater than 5"; } (Greater Than) - No output
- if ($x < 5) { echo "x is less than 5"; } (Less Than) - Outputs: "x is less than 5"
- if ($x >= 5) { echo "x is greater than or equal to 5"; } (Greater Than or Equal) - Outputs: "x
is greater than or equal to 5"
- if ($x <= 5) { echo "x is less than or equal to 5"; } (Less Than or Equal) - Outputs: "x is less
than or equal to 5"

Logical Operators

- if ($x > 5 && $y > 3) { echo "x is greater than 5 and y is greater than 3"; } (And) - No
output
- if ($x > 5 || $y > 3) { echo "x is greater than 5 or y is greater than 3"; } (Or) - Outputs: "x is
greater than 5 or y is greater than 3"
- if (!$x) { echo "x is false"; } (Not) - Outputs: "x is false"

String Operators

- $x = 'Hello ' . 'World'; (Concatenation) - $x is now "Hello World"


- $x .= ' World'; (Concatenation and Assignment) - $x is now "Hello World"

Increment/Decrement Operators

- $x++; (Increment) - $x is now 6


- $x--; (Decrement) - $x is now 5

Addition

<!DOCTYPE html>

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 27


<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x + $y;
?>
</body>
</html>

Output:
16
Subtraction

<!DOCTYPE html>
<html>
<body>

<?php
$x = 10;
$y = 6;
echo $x - $y;
?>
</body>
</html>

Output:
4
Multiplication
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x * $y;
?>
</body>
</html>

Output:
60
Division
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x / $y;

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 28


?>
</body>
</html>

Output:
1.6666666666667
Modulus
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x % $y;
?>
</body>
</html>

Output:
4

Exponentiation

<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
echo $x ** $y;
?>
</body>
</html>

Output:
1000

Prof. M.RAJA M.Sc.,M.Phil.,BEd., Page 29

You might also like