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

Unit 1 Introduction to PHP Updated

The document provides an introduction to PHP, a server-side scripting language used for web development, detailing its history, features, and installation process. It covers fundamental concepts such as embedding PHP in HTML, data types, control structures, and error handling, along with practical examples. Additionally, it explains how to send data to web browsers and manage sessions and cookies.

Uploaded by

ajay123456ab
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)
2 views

Unit 1 Introduction to PHP Updated

The document provides an introduction to PHP, a server-side scripting language used for web development, detailing its history, features, and installation process. It covers fundamental concepts such as embedding PHP in HTML, data types, control structures, and error handling, along with practical examples. Additionally, it explains how to send data to web browsers and manage sessions and cookies.

Uploaded by

ajay123456ab
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/ 32

Divya S R, Assistant Professor, Department of Computer Science,

AES National Degree College, Gauribidanur.

Unit 1

Introduction to PHP

Introduction to PHP

PHP, which stands for Hypertext Preprocessor, is a popular server-side scripting language
designed for web development. It is used to create dynamic web pages and can be embedded into
HTML. PHP code is executed on the server, which means the code is processed on the web server
before the result is sent to the web browser. PHP can interact with databases, manage sessions,
create cookies, and generate dynamic page content. It is widely used for building websites and
web applications.
One of the key features of PHP is its ability to seamlessly integrate with various database
management systems, such as MySQL, PostgreSQL, and SQLite, making it an ideal choice for building
dynamic, database-driven websites and web applications.
PHP code is typically processed on a web server by a PHP interpreter, which generates the
resulting web page. This allows PHP to create dynamic web content, interact with databases,
handle forms, and perform many other tasks needed for web development.

History and Features of PHP


History of PHP:
 Created by Rasmus Lerdorf in 1994 for personal use.
 PHP/FI (Personal Home Page/Forms Interpreter) released in 1995.
 PHP 3 introduced in 1997 with improved performance and OOP support.
 PHP 4 (2000) brought sessions and enhanced database support.
 PHP 5 (2004) featured Zend Engine 2 for better performance and OOP features.
 PHP 7 (2015) marked by significant performance improvements.
 PHP 8 (2020) introduced JIT compilation and several new features.

Features of PHP: (IN SHORT ANSWER)


 Server-side scripting for dynamic web page generation.
 Open-source, freely available, and cross-platform.
 Supports various databases including MySQL, PostgreSQL, SQLite.
 Extensive library support and integration with other technologies.
 Active community contributing to its development and support.

1
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

(IN LONG ANSWER)


1. 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.
2. 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.
3. Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
4. Embedded:
PHP code can be easily embedded within HTML tags and script.
5. Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one
OS can be easily executed in other OS also.
6. Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
7. Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g.,
E_ERROR, E_WARNING, E_STRICT, E_PARSE.
8. Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the time of
execution based on the type of data it contains on its value.

2
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

9. Web servers Support:


PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc.
10. Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent
threads and malicious attacks.
11. Control:
Different programming languages require long script or code, whereas PHP can do the same work in a few
lines of code. It has maximum control over the websites like you can make changes easily whenever you
want.
12. A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online help, and
FAQs. Learning PHP from the communities is one of the significant benefits.

Installation & Configuration of PHP


We will learn how to install the XAMPP server on windows platform step by step. Follow the below steps
and install the XAMPP server on your system.
Step 1: Click on the above link provided to download the XAMPP server according to your window
requirement.

3
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP to make changes
in your system. A window will pop-up, where you have to click on the Next button.

Step 3: Here, select the components, which you want to install and click Next.

4
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.

Step 5: Click Next and move ahead.

5
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.

Step 7: A finish window will display after successful installation. Click on the Finish button.

6
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Step 8: Choose your preferred language.

Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php program on the
localhost.
How to run PHP programs on XAMPP, see in the next tutorial.

7
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Step 10: If no error is shown, then XAMPP is running successfully.

Embedding PHP code in Your Web Pages


Embedding PHP code in your web pages allows you to dynamically generate content and interact with
databases, sessions, and other server-side functionality. Here's how you can embed PHP code in your web
pages:
1. File Extension: PHP code should be saved in files with a .php extension.
2. Opening and Closing Tags: PHP code is enclosed within <?php and ?> tags. Everything
between these tags is treated as PHP code and will be executed on the server.
3. HTML Integration: You can mix HTML and PHP code within the same file. PHP code can be
embedded anywhere within HTML, including within attributes of HTML tags.
4. Echoing Content: To output content to the browser, you can use the echo or print
statements.
5. Variables: PHP variables start with a dollar sign ($). They can store various types of data,
including strings, numbers, arrays, objects, etc.
6. Control Structures: PHP supports control structures like if, else, elseif, while, for, foreach,
etc., which allow you to control the flow of your code.
7. Include Files: You can include other PHP files using include or require statements, which allows
you to reuse code across multiple pages.

8
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Here's a simple example of embedding PHP code in an HTML file:


<!--DOCTYPE html-->
<html>
<head>
<title>PHP Example</title>
</head>
<body>

<h1>Hello </h1>
<?php
echo "Hello world";
?>
</body>
</html>
Output

When you access this PHP file through a web server, the PHP code will be executed on the server, and the
resulting HTML will be sent to the browser for display. The browser will only see the HTML output and
won't know that PHP was used to generate it.

9
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Understanding PHP
Understanding PHP (Hypertext Preprocessor) is essential for developing dynamic web applications.

1. What is PHP?
o PHP is a server-side scripting language used for web development. It's embedded within
HTML to create dynamic content, interact with databases, manage sessions, and perform
other server-side tasks.
2. Basic Syntax:
o PHP code is enclosed within <?php and ?> tags.
o Statements end with a semicolon (;).
3. Variables:
o Variables in PHP start with a dollar sign ($), followed by the variable name.
o They can store various data types like strings, integers, floats, arrays, objects, etc.
o Example: $name = "John";
4. Data Types:
o PHP supports several data types including:
 String
 Integer
 Float (floating-point numbers)
 Boolean (true or false)
 Array
 Object
 Null
 Resource
5. Operators:
o PHP supports various operators like arithmetic, assignment, comparison, logical, etc.
6. Control Structures:
o PHP provides control structures like if, else, elseif, switch, while, do-while, for,
foreach, etc., for flow control.
7. Functions:
o PHP allows you to define and call functions to organize code into reusable blocks.
o Built-in functions are also available for common tasks.
8. Arrays:
o Arrays in PHP can store multiple values in a single variable.
o They can be indexed arrays, associative arrays, or multidimensional arrays.
9. Forms Handling:
10
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
o PHP can process form data submitted via GET or POST methods using $_GET and
$_POST superglobal arrays.
10. Database Interaction:
o PHP can interact with databases like MySQL, PostgreSQL, SQLite, etc., using database-
specific extensions (e.g., mysqli, PDO).
o It allows executing SQL queries, fetching results, and performing database
transactions.
11. File Handling:
o PHP provides functions for handling files and directories on the server, such as reading,
writing, deleting files, etc.
12. Sessions and Cookies:
o PHP enables session management and cookie handling for maintaining user state across
multiple requests.
13. Error Handling:
o PHP offers error reporting and handling mechanisms to debug and manage errors gracefully.
14. Security:
o PHP provides features like input validation, data sanitization, and protection against
common security vulnerabilities like SQL injection, XSS (Cross-Site Scripting), CSRF
(Cross-Site Request Forgery), etc.
15. Object-Oriented Programming (OOP):
o PHP supports object-oriented programming concepts like classes, objects, inheritance,
encapsulation, and polymorphism.

Understanding PHP, HTML and Whitespace


In PHP, when generating HTML dynamically, you have control over how white space is handled. PHP itself
doesn't alter the behavior of HTML white space, but you can manipulate white space within PHP code
before outputting HTML.
Here are some common examples:
1. PHP and HTML: PHP code is typically embedded within HTML files. The PHP code is enclosed
between <? php and ?> tags, and it can be placed anywhere within the HTML document.

11
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
<!-- DOCTYPE html-->
<html>
<head>
<title> PHP and HTML </title>
</head>
<h1>
<?php
echo "Divya","Setty";
?>
</h1>
<p> Embedding PHP and HTML </p>
</body>
</html>

Output:

12
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

2. Whitespace in HTML and PHP:


In HTML, whitespace (spaces, tabs, line breaks) is generally insignificant. Multiple consecutive
spaces are treated as a single space and line breaks are usually ignored.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Whitespace Example</title>
</head>
<body>
<?php
// PHP code block
$name = "John"; // Multiple spaces before and after the assignment
$age = 30; // Spaces between the variable name and value
$country= "USA"; // Uneven spacing around the assignment
?>

<h1>Welcome, <?php echo $name; ?>!</h1>


<p>You are <?php echo $age; ?> years old and from <?php echo $country; ?>.</p>
</body>
</html>

Output:

13
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Writing Comments in PHP


In PHP, comments are used to annotate code for better readability and understanding.
There are two main types of comments in PHP:
1. single-line comments
2. multi-line comments.
1. Single-line comment: Single-line comments start with double slash ( // ) and continue until
the end of the line. They are useful for adding short, inline explanations.
Synatx
// This is a single-line comment

Example :
$name = "John"; // Variable assignment

2. Multi-line comment : Multi-line comments start with /* and end with */. They can span
multiple lines and are useful for longer explanations or commenting out blocks of code.
Syntax
/*
This is a multi-line comment.
It can span multiple lines.
*/

Example:
/*
$name = "John";
$age = 30;
*/

3. Doc Comments (Documentation Comments): Doc comments are a special type of multi-line
comment used to document functions, classes, methods, or variables. They follow a specific
format and are commonly used by automated documentation generators like PHPDoc.

14
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
/**
* This function calculates the sum of two numbers.
*
* @param int $a The first number
* @param int $b The second number
* @return int The sum of $a and $b
*/
function sum($a, $b)
{
return $a + $b;
}

Sending Data to the Web Browser


To send data to a web browser in PHP, you can use various methods to generate and output content
dynamically.
Here are some common approaches:
1. Using echo or print: These functions are used to send data directly to the browser.
Example:
<?php
echo "Hello”, “World!"; // Sending plain text
print("<h1>This is a heading</h1>"); // Sending HTML
?>
Output:

15
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

2. Using HTML and PHP intermixed: You can mix HTML and PHP to generate dynamic content.
<!DOCTYPE html>
<html>
<head>
<title>Whitespace Example</title>
</head>
<body>
<?php
// PHP code block
$name = "John"; // Multiple spaces before and after the assignment
$age = 30; // Spaces between the variable name and value
$country= "USA"; // Uneven spacing around the assignment
?>
<h1>Welcome, <?php echo $name; ?>!</h1>
<p>You are <?php echo $age; ?> years old and from <?php echo $country; ?>.</p>
</body>
</html>

Output:

3. Using header() function: This function sends a raw HTTP header to the browser.

Example:
<?php
header('Location: http://www.example.com/');
echo “Welcome”,”to”,”Computer”,”lab”;
?>

16
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Example:

Or
<?php
header(“Content-Type: text/plain“);
echo “Welcome”,”to”,”Computer”,”lab”;
?>

Output

4. Using Server-Side Includes (SSI): If your server is configured for it, you can include the output
of another script directly in your PHP file.
Example:
<?php
include 'footer.php';
?>

17
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

5. Using Output Buffering: You can use output buffering to capture the output of PHP code and
then decide whether to send it or discard it.
Example:
<?php
ob_start();
echo "Hello, World!";
$content = ob_get_clean();
echo $content;
?>

6. Sending JSON data: For AJAX requests or API responses, you can encode data as JSON and send
it to the browser.
Example:
<?php
$data = array("name" => "John", "age" => 30, "city" => "New York");
header('Content-Type: application/json');
echo json_encode($data);
?>
Data types in PHP
In PHP, data types can be classified into two main categories: primitive data types and compound data
types. Primitive Data Types:
1. Scalar Types:
o Integer: Represents whole numbers, such as 1, 100, -500, etc.
Example:
```php
$integerVar = 10;
```
Note: Single triple quote (‘’’) or double triple quotes(“””) used to represent multi-line strings.

o Float (Floating Point Numbers): Represents numbers with decimal points, such as 3.14,
-0.5, etc.
Example:
```php
$floatVar = 3.14;
```

18
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

o String: Represents a sequence of characters, enclosed within single quotes (' ') or
double quotes (" ").
Example:
``php
$stringVar = "Hello, World!";
```
o Boolean: Represents a binary value, either true or false.
Example:
```php
$boolVar = true;
```
2. Special Scalar Types:
o NULL: Represents a variable with no value or a variable that has been explicitly set to
null.
Example:
```php
$nullVar = null;
```
Compound Data Types:
1. Array: Represents a collection of elements, which can be indexed or associative. Indexed arrays
use numeric keys, while associative arrays use string keys.
Example:
// Indexed array
$indexedArray = array(1, 2, 3);
// Associative array
$assocArray = array("name" => "John", "age" => 30);
// Multidimensional array
$multiArray = array(
array("John", "Doe"),
array("Jane", "Smith")
);
```

19
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

2. Object: Represents instances of classes. An object is an instance of a class, and it can contain
properties and methods.
Example:
class Person
{
public $name;
public $age;

function __construct($name, $age)


{
$this->name = $name;
$this->age = $age;
}
}
$personObj = new Person("John", 30);

3. Resource: Represents a special type that holds a reference to an external resource, such as a
database connection or file handle.
Example:
```php
$file = fopen("example.txt", "r");
```

Other Data Types:


1. Callable: Represents a variable that can be called as a function. This can be a function name, a
closure, an object implementing the _ _invoke() method, or any other valid PHP callable entity.

These are the main data types in PHP, and understanding them is crucial for effective programming. They
provide flexibility and versatility in handling different types of data in PHP applications.
Example:
// Regular function
function regularFunction($name)
{
echo "Hello, $name!";
}

20
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

// Callable variable pointing to a regular function


$callable1 = 'regularFunction';

// Calling the regular function using the callable variable


$callable1("John");

// Anonymous function (closure)


$closure = function($name)
{
echo "Hello, $name!";
};

// Callable variable pointing to an anonymous function


$callable2 = $closure;

// Calling the anonymous function using the callable variable


$callable2("Jane");

// Class with __invoke() method


class Greeting
{
public function __invoke($name)
{
echo "Hello, $name!";
}
}

// Creating an object of the class


$greetingObject = new Greeting();

// Callable variable pointing to an object's __invoke() method


$callable3 = $greetingObject;

// Calling the object's __invoke() method using the callable variable


$callable3("Jack");
21
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Keywords in PHP
In PHP, keywords are reserved words that have special meanings and are used to perform specific tasks
or define certain elements of the language syntax. These keywords cannot be used as identifiers (such as
variable names, function names, etc.) because they have predefined meanings within the PHP language.
Here are some important categories of keywords in PHP:
1. Control Structures Keywords:
o if, else, elseif: Used for conditional statements.
o switch, case, break, default: Used for switch statements.
o while, do, for, foreach: Used for loop control.
o continue, break: Used for loop control flow.
2. Function and Class Keywords:
o function: Used to define a function.
o class, extends, implements: Used to define classes and interfaces.
o new: Used to instantiate objects.
o return: Used to return values from functions.
o static: Used to declare static properties and methods in classes.
3. Variable Keywords:
o global: Used to access global variables inside functions.
o static: Used to declare static variables inside functions or methods.
o const: Used to declare constants.
4. Include/Require Keywords:
o include, include_once: Used to include and execute a file.
o require, require_once: Similar to include, but generates a fatal error if the file cannot be
included.
5. Namespace Keywords:
o namespace, use: Used to define and import namespaces.
6. Error Control Keywords:
o try, catch, finally: Used for exception handling.
o throw: Used to throw exceptions.
7. Other Keywords:
o echo, print: Used to output data.
o isset, empty: Used to check variable existence and emptiness.
o define: Used to define constants.
o abstract, final, public, protected, private: Used for visibility and inheritance control in
classes.
22
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Using these keywords correctly and understanding their functionalities is essential for writing clear and
efficient PHP code. Improper use or misunderstanding of keywords can lead to syntax errors or
unexpected behavior in your PHP applications.

Using Variables
Using variables in PHP is straightforward. Variables are used to store and manipulate data within a PHP
script. Here's how you can use variables in PHP:
1. Variable Declaration and Assignment: You can declare a variable in PHP using the $ symbol
followed by the variable name. You can then assign a value to the variable using the assignment
operator =.
Example:
$name = "John";
$age = 30;

2. Variable Naming Rules:


 Variable names in PHP must start with a letter or an underscore (_).
 Variable names can contain letters, numbers, and underscores.
 Variable names are case-sensitive ($name is different from $Name).

3. Variable Interpolation: In double-quoted strings, you can directly include variables within the
string, and their values will be interpolated.
Example:
echo "My name is $name and I am $age years old.";

4. Concatenation: You can concatenate variables with strings or other variables using the
concatenation operator.
Example:
echo "My name is " . $name . " and I am " . $age . " years old.";

5. Variable Scope: Variables in PHP have different scopes:


 Global scope: Variables declared outside of functions are in the global scope and can be accessed
anywhere in the script.
 Local scope: Variables declared inside functions are in the local scope and can only be accessed
within that function.

23
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Example
$globalVar = "I'm a global variable.";
function myFunction()
{
$localVar = "I'm a local variable.";
echo $globalVar; // Accessing global variable inside function
}
myFunction();
echo $localVar; // This will cause an error because $localVar is not accessible outside the function.

6. Variable Types: PHP is loosely typed, meaning you don't need to declare the type of a variable
explicitly. PHP automatically converts the variable to the appropriate type depending on the
context.
Example
$num = 10; // Integer
$floatNum = 3.14; // Float
$str = "Hello"; // String
$bool = true; // Boolean

7. Dynamic Variables: You can use variable variables to create variable names dynamically.
Example:
$varName = "name";
$$varName = "John"; // Creates $name variable with value "John"
echo $name; // Outputs: John

These are some basic examples of how to use variables in PHP. Variables are fundamental to PHP
programming and are used extensively in writing dynamic and interactive web applications.

Constants in PHP
In PHP, constants are like variables but once defined, they cannot be changed or redefined during
the execution of the script. They are useful for defining values that remain constant throughout the
execution of a script.
Constants are defined using the define() function or the const keyword. Here's how you can define
constants:

24
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

1. Using define() function:


Example
define("PI", 3.14);

2. Using const keyword (available since PHP 5.3.0):


Example:
const PI = 3.14;

Once defined, constants can be accessed throughout the script without the need to prepend the $ symbol.
Example:
echo PI; // Outputs: 3.14

Here are some important points about constants in PHP:


 Constants are case-sensitive by default.
 By convention, constant names are usually uppercase.
 Constants can be defined with scalar values (string, integer, float, or boolean).
 Constants can also be defined with arrays since PHP 7.0.0.
 Constants are global in scope and can be accessed from anywhere in the script.
 Constants cannot be redefined or unset once they are defined.
 Constants can be used in any context where an expression is allowed.

Here's an example illustrating the use of constants:


Example:
// Define constants
define("SITE_NAME", "My Website");
const PI = 3.14;

// Access constants
echo SITE_NAME; // Outputs: My Website
echo PI; // Outputs: 3.14

// Constants can be used in expressions


$radius = 5;
$area = PI * $radius * $radius;
echo $area; // Outputs: 78.5
25
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Constants are useful for storing configuration values, defining database credentials, or any other value
that should remain constant throughout the execution of a script.

Expressions in PHP
In PHP, an expression is a combination of values, variables, operators, and function calls that evaluates to
a single value. Expressions can be simple or complex, and they are used extensively in PHP code for
performing calculations, comparisons, and other operations.

Here are some examples of expressions in PHP:

1. Arithmetic Expressions: Arithmetic expressions involve mathematical operations such as


addition, subtraction, multiplication, and division.
Example:
$result = 5 + 3 * 2; // Evaluates to 11

2. String Concatenation: String concatenation involves joining two or more strings together using
the concatenation operator (.).
Example:
$greeting = "Hello, " . "World!"; // Evaluates to "Hello, World!"

3. Comparison Expressions: Comparison expressions evaluate to a boolean value (true or false)


based on the comparison of two values.
Example:
$isGreater = 10 > 5; // Evaluates to true

4. Logical Expressions: Logical expressions involve logical operations such as AND (&&), OR (||),
and NOT (!).
Example:
$isTrue = true && false; // Evaluates to false

5. Conditional (Ternary) Expressions: Conditional expressions allow you to choose between two
values based on a condition.

26
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
$age = 20;
$isAdult = ($age >= 18) ? "Yes" : "No"; // Evaluates to "Yes"

6. Function Call Expressions: Function call expressions involve calling a function and passing
arguments to it.
Example:
$length = strlen("Hello"); // Evaluates to 5

7. Array Expressions: Array expressions involve creating or accessing elements of an array.


Example:
$arr = [1, 2, 3];
$value = $arr[1]; // Evaluates to 2

8. Object Expressions: Object expressions involve accessing properties or calling methods of an


object.
Example:
class MyClass
{
public $name = "John";
public function greet()
{
return "Hello, " . $this->name . "!";
}
}
$obj = new MyClass();
$message = $obj->greet(); // Evaluates to "Hello, John!"

These are some common examples of expressions in PHP. Expressions are fundamental to writing PHP
code, and they are used extensively for performing various tasks such as calculations, string manipulation,
and decision making.

27
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

Operators in PHP
Some of the operators in PHP is
1. Arithmetic Operators: Arithmetic operators used to perform Arithmetic Operations.

 + Addition
 - Subtraction
 * Multiplication
 / Division
 % Modulus (returns the remainder of a division)

Example:
$num1 = 10;
$num2 = 5;
// Addition
$sum = $num1 + $num2; // $sum contains 15
// Subtraction
$difference = $num1 - $num2; // $difference contains 5
// Multiplication
$product = $num1 * $num2; // $product contains 50
// Division
$quotient = $num1 / $num2; // $quotient contains 2
// Modulus
$remainder = $num1 % $num2; // $remainder contains 0

2. Assignment Operators: Assigning one variable to another variable.


 = Assignment
 += Addition assignment
 -= Subtraction assignment
 *= Multiplication assignment
 /= Division assignment
 %= Modulus assignment
 .=, .=+, .-=, .*=, ./=, .=% String concatenation assignment

28
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
$x = 10;
$y = 5;

// Addition assignment
$x += $y; // $x now contains 15
// Subtraction assignment
$x -= $y; // $x now contains 10
// Multiplication assignment
$x *= $y; // $x now contains 50
// Division assignment
$x /= $y; // $x now contains 10
// Modulus assignment
$x %= $y; // $x now contains 0

3. Comparison Operators: Comparing one variable with another variable.

Example:
$a = 10;
$b = 5;

// Equal to
$result1 = ($a == $b); // $result1 contains false
// Not equal to
$result2 = ($a != $b); // $result2 contains true
// Greater than
$result3 = ($a > $b); // $result3 contains true
// Less than or equal to
$result4 = ($a <= $b); // $result4 contains false

4. Logical Operators: It is used to display true or false.


Example:
$p = true;
$q = false;

29
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.

// Logical AND
$result5 = ($p && $q); // $result5 contains false
// Logical OR
$result6 = ($p || $q); // $result6 contains true
// Logical NOT
$result7 = !$p; // $result7 contains false

5. String Concatenation Operator: Joining one string to another string


Example:
$str1 = "Hello, ";
$str2 = "World!";
$greeting = $str1 . $str2; // $greeting contains "Hello, World!"

6. Increment/Decrement Operators: for increment ++ and decrement --


Example
$num = 10;
// Increment
$num++; // $num now contains 11
// Decrement
$num--; // $num now contains 10

7. Array Operators:
 + Union (combines arrays)
 == Equality (returns true if arrays have the same key/value pairs)
 === Identity (returns true if arrays have the same key/value pairs in the same order and of the
same types)
In PHP, array operators are used to manipulate arrays. There are mainly two array operators: union (+) and
equality (==, ===).
1. Union Operator (+):
o The union operator (+) combines two arrays. It returns an array containing all the elements
from both arrays, with duplicate values removed. If there are duplicate keys, the elements
from the left-hand array will be used, and the elements from the right-hand array will be
ignored.

30
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
Example:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "blueberry", "c" => "cherry");
$result = $array1 + $array2;
print_r($result);

Output:
Array
(
[a] => apple
[b] => banana
[c] => cherry
)
2. Equality Operators (==, ===):
 The equality operators (==, ===) are used to compare arrays for equality.
 The == operator checks if two arrays have the same key/value pairs, regardless of the order of
elements.
 The === operator checks if two arrays have the same key/value pairs in the same order and of the
same types.

Example:
$array1 = array("a" => "apple", "b" => "banana");
$array2 = array("b" => "banana", "a" => "apple");
// Using == operator
if ($array1 == $array2)
{
echo "Arrays are equal";
} else
{
echo "Arrays are not equal";
}
// Using === operator
if ($array1 === $array2)
{
echo "Arrays are identical";
} else
31
UNIT 1
Divya S R, Assistant Professor, Department of Computer Science,
AES National Degree College, Gauribidanur.
{
echo "Arrays are not identical";
}

Output:
Arrays are equal
Arrays are not identical

8. Ternary Operator:
The ternary operator in PHP is a shorthand way of writing conditional statements. It allows you to express
a conditional expression in a single line. The syntax of the ternary operator is:

General Syntax is
(condition) ? value_if_true : value_if_false;

Here's an example demonstrating the use of the ternary operator in PHP:


Example:
$age = 20;
// Using the ternary operator to determine if the person is an adult
$isAdult = ($age >= 18) ? "Yes" : "No";
echo "Is the person an adult? " . $isAdult;

In this example:
 If the condition $age >= 18 evaluates to true, the value "Yes" is assigned to the variable
$isAdult.
 If the condition evaluates to false, the value "No" is assigned to the variable $isAdult.

9. Type Operators:
 instanceof Checks if an object is an instance of a specific class

10. Error Control Operator:


 @ Suppresses error messages

These examples illustrate how different operators are used in PHP to perform arithmetic
calculations, comparisons, logical operations, string concatenation, and more. Understanding and using
operators effectively is crucial for writing PHP code efficiently.
32
UNIT 1

You might also like