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

1_PHP

Uploaded by

pjay27470
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)
123 views

1_PHP

Uploaded by

pjay27470
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/ 30

Unit 1: PHP Fundamentals

1.1 Concepts of PHP and its Introduction


1.2 Php syntax: variables, constants, echo and print commands
1.3 Data types
1.4 Operators, Conditional Statements (if. Else, Switch. Case), Arrays
1.5 Sorting Arrays, Php Loops

1.1 Concepts of PHP and its Introduction

• PHP, which stands for Hypertext Preprocessor, is a widely used programming language
specifically designed for web development.
• PHP was created by Rasmus Lerdorf in 1994 and become one of the most popular server-
side scripting languages for building dynamic websites and web applications.
• It is open-source, which means it is free to download and use. It is very simple to learn and
use. The files have the extension “.php”.
• PHP is embedded within HTML code and executed on the server, allowing developers to
generate dynamic content and interact with databases.
• PHP offers a wide range of features and functionalities that make web development efficient
and flexible.
• PHP is an interpreted language and 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.

The key concepts of PHP:

1. Purpose: PHP was created to enhance the capabilities of static HTML by adding
dynamic features. It allows you to embed PHP code within HTML documents, generating
dynamic content, interacting with databases, handling form data, and performing
various server-side tasks.
2. Syntax: PHP code is typically embedded within special delimiters <?php and ?>,
although the short tag <?= ?> is also commonly used. PHP statements end with a
semicolon (;). It follows a C-style syntax, making it relatively easy for developers familiar
with languages like C, Java, or JavaScript to learn and use PHP.
3. Variables: PHP variables start with a dollar sign ($) followed by the variable name. PHP
has dynamic typing, meaning you don't need to declare variable types explicitly.
Variables can store various types of data, including strings, numbers, arrays, objects, etc.
4. Control Structures: PHP supports familiar control structures like if-else statements,
loops (for, while, do-while), switch statements, and more. These control structures allow
you to make decisions, repeat actions, and control the flow of your program based on
certain conditions.
5. Functions: PHP provides a vast collection of built-in functions for performing common
tasks, such as manipulating strings, working with arrays, handling file operations,
performing mathematical calculations, and interacting with databases. You can also
create your own custom functions to encapsulate reusable code.
6. Arrays: Arrays are a fundamental data structure in PHP. They can store multiple values
of different types and allow you to access and manipulate data efficiently. PHP supports
indexed arrays, associative arrays (key-value pairs), and multidimensional arrays.
7. File Handling: PHP provides various functions for working with files and directories.
You can read from and write to files, create or delete files and directories, manipulate
file permissions, and perform other file-related operations.
8. Database Connectivity: PHP has extensive support for connecting to databases,
including popular database management systems like MySQL, PostgreSQL, SQLite, etc.

Educator: Asst. Prof. Twinkle Panchal 1


Unit 1: PHP Fundamentals

You can execute SQL queries, retrieve data, insert or update records, and manage
database connections using PHP's database extensions.
9. Object-Oriented Programming (OOP): PHP supports object-oriented programming
concepts, allowing you to create classes, objects, and methods. You can utilize OOP
principles like encapsulation, inheritance, and polymorphism to structure your code and
build modular and reusable components.
10. Web Development: PHP has a strong focus on web development. It offers various
features and functions specifically tailored for building dynamic web applications,
including handling HTTP requests and responses, managing sessions and cookies,
processing form data, working with web services, and generating dynamic HTML
content.

The key features of PHP

1. Simplicity: PHP has a relatively simple and easy-to-understand syntax, making it


accessible to beginners. It is designed to be user-friendly and forgiving, allowing
developers to quickly start building web applications.
2. Server-side Scripting: PHP is primarily used as a server-side scripting language, which
means it runs on the server and generates dynamic web content that is then sent to the
client's browser. This enables the creation of dynamic and interactive web applications.
3. Wide Platform Support: PHP is a cross-platform language, supporting major operating
systems like Windows, macOS, Linux, and Unix. It can be deployed on various web
servers, including Apache, Nginx, and Microsoft IIS.
4. Embeddable: PHP code can be easily embedded within HTML markup, allowing for
seamless integration of dynamic content with static web pages. This blending of PHP
and HTML makes it convenient to generate dynamic elements, such as displaying
database records or processing form data.
5. Extensive Library Support: PHP has a rich ecosystem of libraries and frameworks that
extend its capabilities and simplify common web development tasks. Frameworks like
Laravel, Symfony, and CodeIgniter offer features such as routing, database abstraction,
authentication, and templating, enabling rapid application development.
6. Database Integration: PHP offers excellent support for interacting with databases. It
has built-in extensions and functions for connecting to various database management
systems like MySQL, PostgreSQL, SQLite, Oracle, and more. This makes it convenient to
perform database operations, such as querying, inserting, updating, and deleting data.
7. Scalability: PHP can handle high traffic websites and scale efficiently. It can be used in
conjunction with caching mechanisms, load balancers, and other optimization
techniques to enhance performance and handle large volumes of requests.
8. Security: PHP has evolved to address security concerns and provides features to
mitigate common vulnerabilities. It offers built-in functions for handling input
validation, sanitizing user data, preventing SQL injection, and protecting against cross-
site scripting (XSS) attacks. Adhering to secure coding practices and using secure
frameworks is important for robust PHP application development.

These features contribute to PHP's popularity and widespread usage in web development. Its
combination of simplicity, flexibility, and extensive community support makes it an attractive
choice for building dynamic and interactive web applications.

Educator: Asst. Prof. Twinkle Panchal 2


Unit 1: PHP Fundamentals

1.2 PHP Syntax: Variables, Constants, Echo And Print Commands

1.2 PHP Syntax:

• The structure which defines PHP, is called PHP syntax.


• The PHP script is executed on the server and the HTML result is sent to the browser. It
can normally have HTML and PHP tags.
• PHP or Hypertext Preprocessor is a widely used open-source general-purpose scripting
language and can be embedded with HTML.
• PHP files are saved with the “.php” extension.
• PHP scripts can be written anywhere in the document within PHP tags along with
normal HTML.

Escaping To PHP:
The mechanism of separating a normal HTML from PHP code is called the mechanism of
Escaping To PHP.
Writing the PHP code inside <?php ….?> is called Escaping to PHP.
There are various ways in which this can be done. Few methods are already set by default but in
order to use few others like Short-open or ASP-style tags, we need to change the configuration
of the php.ini file. These tags are used for embedding PHP within HTML.
There are 4 such tags available for this purpose.
1. Canonical PHP Tags:
The script starts with <?php and ends with ?>. These tags are also called ‘Canonical PHP tags’.
Everything outside of a pair of opening and closing tags is ignored by the PHP parser. The open
and closing tags are called delimiters. Every PHP command ends with a semi-colon (;). Let’s look
at the hello world program in PHP.

<?php Output:
# This indicates a comment in PHP Hello, world!
echo "Hello, world!";
?>

2. SGML or Short HTML Tags:

These are the shortest option to initialize a PHP code. The script starts with <? and ends with
?>. This will only work by setting the short_open_tag setting in the php.ini file to ‘on’.

<? Output:
# before using this type of tag one should keep Hello, world!
the short_open_tag value to ‘ON’ from php.ini

echo "Hello, world!";


?>

Educator: Asst. Prof. Twinkle Panchal 3


Unit 1: PHP Fundamentals

3. HTML Script Tags:

These are implemented using script tags. This syntax is removed in PHP 7.0.0. So it’s no more
used.

<script language="php"> Output:


echo "hello world!"; hello world!
</script>

4. ASP Style Tags:

To use this we need to set the configuration of the php.ini file. These are used by Active
Server Pages to describe code blocks. These tags start with <% and end with %>.

<% Output:
# Can only be written if setting is hello world
turned onto allow %
echo "hello world";
%>

1.2.1 PHP Variables:

In PHP, variables are used to store and manipulate data. They provide a way to hold values that
can be used and modified throughout your PHP script. Here's an overview of PHP variables:

1. Variable Declaration and Assignment:


• Variables in PHP are declared using the dollar sign (`$`) followed by the variable name.
• The variable name must start with a letter or underscore and can contain letters,
numbers, and underscores.
• PHP has dynamic typing, so you don't need to specify the variable type explicitly.
• Variables are assigned values using the assignment operator (`=`).
• PHP is a loosely typed language, it means PHP automatically converts the variable to its
correct data type.

Here's an example of variable declaration and assignment:

$name = "Sutex"; // String variable


$age = 25; // Integer variable
$pi = 3.14; // Float variable
$isStudent = true; // Boolean variable

2. Variable Naming Conventions:


• It's a good practice to use descriptive names for variables that reflect their purpose.
• Variable names are case-sensitive in PHP. For example, `$name` and `$Name` are
considered different variables.
• Avoid using reserved keywords as variable names (e.g., `if`, `for`, `echo`, etc.).
• Follow a consistent naming convention, such as camelCase or snake_case.

3. Variable Scope:
• PHP variables have different scopes that define their accessibility.

Educator: Asst. Prof. Twinkle Panchal 4


Unit 1: PHP Fundamentals

• The scope of a variable determines where it can be accessed within a PHP script.
• PHP has four variable scopes: global, local, static, and function parameters.
• Global variables can be accessed from anywhere in the script, whereas local variables
are limited to the scope they are declared in.
• Static variables retain their values across function calls.
• Function parameters are variables that receive values when a function is called.
• Variable scope is an important concept to understand when dealing with PHP functions
and includes considerations for avoiding naming conflicts and managing variable
visibility.
Here's an explanation of the four variable scopes in PHP, along with examples:

3.1. Global Scope:


• Variables declared outside of any function or class have a global scope.
• Global variables can be accessed from anywhere in the PHP script, including inside
functions and classes.
• To access the global variable within a function, use the global keyword before the
variable. However, these variables can be directly accessed or used outside the function
without any keyword.
• Therefore there is no need to use any keyword to access a global variable outside the
function.
Example:
<?php Output:
$name = "Sanaya Sharma"; //Global Variable Variable inside the
function global_var() function: Sanaya
{ Sharma
global $name; Variable outside the
function: Sanaya
echo "Variable inside the function: ". $name;
Sharma
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Note: Without using the global keyword, if you try to access a global variable inside the
function, it will generate an error that the variable is undefined.

Example:
<?php Output:
$name = "Sanaya Sharma"; //global variable Notice: Undefined variable: name in
function global_var() D:\xampp\htdocs\program\p3.php
{ on line 6
echo "Variable inside the function: ". Variable inside the function:
$name; echo "</br>";
}
global_var();
?>

Educator: Asst. Prof. Twinkle Panchal 5


Unit 1: PHP Fundamentals

Using $GLOBALS instead of global


Another way to use the global variable inside the function is predefined $GLOBALS array.
Example:
<?php Output:
$num1 = 5; //global variable Sum of global variables is: 18
$num2 = 13; //global variable
function global_var()
{
$sum = $GLOBALS['num1'] +
$GLOBALS['num2']; echo "Sum of global
variables is: " .$sum;
}
global_var();
?>
If two variables, local and global, have the same name, then the local variable has
higher priority than the global variable inside the function.

Example:
<?php Output:
$x = 5; function Value of x: 7
mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Note: local variable has higher priority than the global variable.

3.2. Local Scope:


- Variables declared within a function have a local scope.
- Local variables are accessible only within the function where they are defined.
- They cannot be accessed outside of the function.
- Here's an example:

function testLocalScope() {
$localVar = 20;
echo $localVar;
}

testLocalScope(); // Outputs: 20

echo $localVar; // Error: Undefined variable 'localVar'

Educator: Asst. Prof. Twinkle Panchal 6


Unit 1: PHP Fundamentals

3.3. Static Scope:


- Static variables are declared using the `static` keyword inside a function.
- Static variables retain their values between multiple calls to the function.
- They are initialized only once, during the first call to the function.
- Here's an example:

function incrementCounter() {
static $counter = 0;
$counter++;
echo $counter . "<br>";
}

incrementCounter(); // Outputs: 1
incrementCounter(); // Outputs: 2
incrementCounter(); // Outputs: 3

4. Variable Output:
• You can output the value of a variable using various PHP constructs, such as `echo`,
`print`, or by embedding the variable within double-quoted strings.
• The `echo` and `print` statements have been covered in a previous response.
• Here's an example of variable output using `echo`:

$name = "Ram Chandra"; Output:


$age = 25;
echo "Name: " . $name . "<br>"; Name: Ram Chandra
echo "Age: " . $age; Age: 25

These are the fundamentals of PHP variables. They allow the storage and manipulation of data
within PHP scripts, making them dynamic and interactive. Variables play a crucial role in web
development by facilitating the handling of user input, database interactions, and dynamic
content generation

PHP $ and $$ Variables


The $var (single dollar) is a normal variable with the name var that stores any value like
string, integer, float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside
it.
Example:
Example 1: Explanation:
<?php In the above example, we have assigned a
$x = "abc"; value to the variable x as abc. Value of
$$x = 200; reference variable $$x is assigned as 200.
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>

Educator: Asst. Prof. Twinkle Panchal 7


Unit 1: PHP Fundamentals

Example 2: Explanation:
<?php In the above example, we have assigned a
$x="U.P"; value to the variable x as U.P. Value of
$$x="Lucknow"; reference variable $$x is assigned as
echo $x. "<br>"; Lucknow.

echo $$x. "<br>";


echo "Capital of $x is " . $$x;
?>
Example 3: Explanation:
<?php In the above example, we have assigned a
$name="Cat"; value to the variable name Cat. Value of
${$name}="Dog"; reference variable ${$name} is assigned as
${${$name}}="Monkey"; Dog and ${${$name}} as Monkey.
echo $name. "<br>";
echo ${$name}. "<br>";
echo $Cat. "<br>";
echo ${${$name}}. "<br>";
echo $Dog. "<br>"; ?>

1.2.2 PHP Constants

In PHP, constants are identifiers that hold values that cannot be changed during the execution of
the script. Constants are useful for storing values that remain constant throughout the code.
Here's an explanation of PHP constants along with an example:

1. Defining Constants:
• Constants are defined using the `define()` function or, starting from PHP 7, using the
`const` keyword.
• Constants are typically named using uppercase letters and underscores to improve
readability.
• The `define()` function takes two arguments: the constant name and its value.

- Here's an example of defining constants using both methods:

// Using define() function


define("SITE_NAME", "My Website");
define("MAX_USERS", 100);

// Using const keyword (PHP 7+)


const PI = 3.14;
const STATUS_ACTIVE = 1;

2. Accessing Constants:
• Constants can be accessed anywhere in the PHP script, similar to global variables.
• Constants are accessed using their names without the leading `$` sign.
- Here's an example of accessing constants:

echo SITE_NAME; Output:

Educator: Asst. Prof. Twinkle Panchal 8


Unit 1: PHP Fundamentals

echo MAX_USERS; My Website


echo PI; 100
echo STATUS_ACTIVE; 3.14
1

3. Constants Value:
• The value of a constant cannot be changed once it is defined.
• Attempting to modify the value of a constant will result in an error.
• Constants can only hold scalar values (e.g., strings, integers, floats, booleans) or arrays.
- Here's an example:

define("WEBSITE_URL", "https://www.example.com");

// Attempting to change the value will result in an error


WEBSITE_URL = "https://www.newexample.com"; // Error: Cannot assign to a constant

echo WEBSITE_URL; // Outputs: https://www.example.com

4. Predefined Constants:
• PHP also provides a set of predefined constants that are available for use without
explicitly defining them.
• These predefined constants are often used to access information about the PHP
environment or to perform certain operations.
- Here's an example of using predefined constants:

echo PHP_VERSION; Outputs:


echo PHP_OS; current PHP version
echo __LINE__; operating system PHP is running on
echo __FILE__; current line number
current file name

Constant() function
There is another way to print the value of constants using constant() function instead of
using the echo statement.

Syntax : constant (name)

Example:
<?php Output:
define("MSG", "WelCome"); WelCome
echo MSG, "</br>"; WelCome
echo constant("MSG");
//both are similar
?>

Note:

Constants in PHP are useful for storing values that should not be changed during the execution
of the script. They provide a way to define and access fixed values that remain consistent

Educator: Asst. Prof. Twinkle Panchal 9


Unit 1: PHP Fundamentals

throughout the code. By convention, constants are often used for configuration settings, system
values, or other unchanging data.

The Differences Between The Constant And Variables In PHP:

Feature Constants Variables


Declared using the define()
Declaration Declared using the $ symbol
function
Value Assigned a value at the time of Assigned a value using the assignment
Assignment declaration operator (=)
Can be updated and changed during
Value Mutability Cannot be changed once defined
execution
Scope can be global, local, or within a
Scope Global scope by default
function
Naming Conventionally defined using Conventionally defined using lowercase or
Convention uppercase letters mixed case letters
Usage Useful for defining fixed values Used for storing and manipulating data
Access Accessed using the constant name Accessed using the variable name

3. echo Command:

In PHP, the `echo` command is used to output text or variable values. It is one of the most
commonly used constructs for displaying content in PHP. Here's an explanation of the `echo`
command with examples:

3.1. Basic Syntax:


• The `echo` command is followed by the content you want to output, enclosed in quotes
(single or double).
• Multiple items can be concatenated using the dot (`.`) operator.
- Here's an example:

<?php Output:
echo "Hello, World!";
?> Hello, World!

3.2. Outputting Variables:


• You can also output the value of a variable using the `echo` command.
• Simply place the variable within the `echo` statement, without quotes.
- Here's an example:

<?php Output:
$name = " Ram Chandra "; Hello, Ram Chandra!
echo "Hello, " . $name . "!";
?>

3.3. HTML Integration:


• Since PHP is often used in conjunction with HTML, the `echo` command is commonly
used to output dynamic content within HTML markup.
• You can embed the `echo` command within HTML tags to display dynamic values.

Educator: Asst. Prof. Twinkle Panchal 10


Unit 1: PHP Fundamentals

- Here's an example:

<?php Output:
$name = "Ram Chandra";
$age = 25; <p>Name: Ram Chandra </p>
echo "<p>Name: " . $name . "</p>"; <p>Age: 25</p>
echo "<p>Age: " . $age . "</p>";
?>

3.4. Newline Character and Escape Characters:


• By default, the `echo` command does not automatically add a newline character.
• To add a newline, you can use the escape sequence `\n` within the `echo` statement.
- Here's an example:
<?php Output:
echo "Line 1\nLine 2\nLine 3";
?> Line 1
Line 2
Line 3

<?php Output:
echo "Hello escape \"sequence\" Hello escape "sequence" characters
characters";
?>

The `echo` command in PHP is a simple yet powerful tool for outputting content. It allows you to
display text, variables, and even integrate with HTML to generate dynamic web content. With
concatenation and HTML integration, you can create versatile and customized output using the
`echo` command in PHP.

4. print Command:

In PHP, the `print` command is used to output text or variable values, similar to the `echo`
command. It is another construct for displaying content in PHP. Here's an explanation of the
`print` command with examples:

4.1. Basic Syntax:


• The `print` command is followed by the content you want to output, enclosed in quotes
(single or double).
• Like `echo`, multiple items can be concatenated using the dot (`.`) operator.
- Here's an example:

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

4.2. Outputting Variables:


• You can also output the value of a variable using the `print` command.
• Place the variable within the `print` statement, without quotes.
- Here's an example:

Educator: Asst. Prof. Twinkle Panchal 11


Unit 1: PHP Fundamentals

<?php Output:
$name = "Ram"; Hello, Ram!
print "Hello, " . $name . "!";
?>
<?php Output:
print "Hello escape \"sequence\" Hello escape "sequence" characters by PHP
characters by PHP print"; print
?>
<?php Output:
$msg="Hello print() in PHP"; Message is: Hello print() in PHP
print "Message is: $msg";
?>

4.3. HTML Integration:


• Similar to the `echo` command, the `print` command is often used to output dynamic
content within HTML markup in PHP.
• You can embed the `print` command within HTML tags to display dynamic values.
- Here's an example:

<?php Output:
$name = "John Doe"; <p>Name: John Doe</p>
$age = 25; <p>Age: 25</p>
print "<p>Name: " . $name . "</p>";
print "<p>Age: " . $age . "</p>";
?>

4.4. Return Value:


• Unlike the `echo` command, which echo does not return a value, the `print` command
returns a value of `1`.
• This can be useful in certain situations where the returned value is needed.
- Here's an example:
$result = print "Hello, World!"; Outputs: 1
echo $result;

The Differences Between The Print And Echo Statements In PHP:

Feature print Statement echo Statement


Syntax print(expression); echo expression;
Return Value Always returns 1 Does not have a return value
Multiple Does not support multiple Supports multiple arguments, separated
Arguments arguments by commas
Speed Relatively slower Relatively faster
Used as an expression or
Usage Used as a statement
statement
Error Handling Can be used as a function Cannot be used as a function
Compatible with older versions
Compatibility Compatible with all versions of PHP
of PHP

Educator: Asst. Prof. Twinkle Panchal 12


Unit 1: PHP Fundamentals

Both print and echo are used to output strings or variables in PHP, but they have some
differences in terms of syntax, return value, usage, and compatibility. echo is generally preferred
for its simplicity and faster execution, while print is useful when you need to use it as an
expression within larger statements.

It's worth noting that the differences between print and echo are relatively minor, and in most
cases, you can use either statement interchangeably based on your preference and specific
requirements.

1.3 Data types

PHP supports several data types to represent different kinds of 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

1. Scalar Types (predefined)

It holds only single value. There are 4 scalar data types in PHP namely 1. String 2. Integer 3.
Float 4. Boolean.

1. String:
• A string is a sequence of characters enclosed in single quotes (`'`) or double quotes (`"`).
• Strings can contain alphanumeric characters, special characters, and escape sequences.
- Example: `"Hello, World!"`

$name = "Ram Chandra";


$message = 'Hello, World!';

2. Integer:
• An integer represents whole numbers without decimal points.
• Positive and negative numbers can be represented using the integer data type.
- Example: `42`, `-10`, `0`

$age = 25;
$quantity = -10;
$count = 0;

3. Float:
• A float (floating-point number) represents numbers with decimal points or fractional
parts.
• Floats can be expressed using decimal notation or scientific notation.
- Example: `3.14`, `-0.5`, `2.5e3` (scientific notation)

$price = 3.99;
$pi = 3.14159;
$scientificNotation = 2.5e3;

4. Boolean:
• A boolean represents a logical value that can be either `true` or `false`.
• Booleans are commonly used in conditions and control structures.

Educator: Asst. Prof. Twinkle Panchal 13


Unit 1: PHP Fundamentals

- Example: `true`, `false`

$isTrue = true;
$isFalse = false;

2. Compound Types (user-defined)

1. Array:
• An array is an ordered collection of values, known as elements.
• Elements in an array can be of any data type, including other arrays.
• Arrays can be indexed numerically or using keys (associative arrays).
- Example: `[1, 2, 3]`, `['name' => 'John', 'age' => 25]`

$numbers = array(1, 2, 3, 4, 5);


$fruits = ['apple', 'banana', 'orange'];
$user = ['name' =>’Ram’, 'age' => 25];

2. Object:
• An object is an instance of a class, representing a specific entity or concept.
• Objects have properties (variables) and methods (functions) associated with them.
• Objects are fundamental to object-oriented programming (OOP) in PHP.
- Example: `$user = new User();`

class User {
public $name;
public $age;
}

$user = new User();


$user->name = 'Ram Chandra';
$user->age = 30;

3. Special Types

1. NULL:
• NULL represents a variable that has no value or is explicitly set to null.
• It is commonly used to indicate the absence of a value or when a variable is intentionally
empty.
- Example: `null`

$value = null;
$data = getSomeData();

if ($data === null) {


echo "No data available.";
}

2. Resource:
• A resource is a special data type that holds a reference to an external resource (e.g.,
database connection, file handle).
• Resources are typically created and managed by PHP extensions and are used for
specific purposes.

Educator: Asst. Prof. Twinkle Panchal 14


Unit 1: PHP Fundamentals

- Example: (Resource)

$file = fopen("data.txt", "r");


$dbConnection = mysqli_connect("localhost", "username", "password", "database");

These are the primary data types in PHP. Each data type serves a specific purpose and allows
you to represent different kinds of values in your PHP code. Understanding data types is crucial
for effectively working with variables, performing operations, and ensuring the correct handling
of data in your PHP applications.

1.4 Operators, Conditional Statements (if. Else, Switch. Case), Arrays

1.4.1 PHP Operators

PHP 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.

1. 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
The exponentiation (**) operator has been introduced in PHP 5.6.

2. 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 $a += $b Addition same as $a = $a + $b
Assign
-= Subtract then $a -= $b Subtraction same as $a = $a - $b
Assign

Educator: Asst. Prof. Twinkle Panchal 15


Unit 1: PHP Fundamentals

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


Assign
/= Divide then $a /= $b Find quotient same as $a = $a / $b
Assign
(quotient)
%= Divide then $a %= $b Find remainder same as $a = $a % $b
Assign
(remainder)

3. 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 $a | $b Bits that are 1 in either $a or $b are set to 1
or)
^ Xor (Exclusive $a ^ $b Bits that are 1 in either $a or $b are set to 0.
or)

~ 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

4. 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

!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they
are not of same 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
> Greater than $a > $b Return TRUE if $a is greater than $b

Educator: Asst. Prof. Twinkle Panchal 16


Unit 1: PHP Fundamentals

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


equal to
>= Greater $a >= $b Return TRUE if $a is greater than or equal $b
than or
equal to
<=> Spaceship $a <=>$b Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b

5. Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.

Operator Name Example Explanation


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

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

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

6. 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

7. 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

Educator: Asst. Prof. Twinkle Panchal 17


Unit 1: PHP Fundamentals

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


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

8. 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 === Return TRUE if $a and $b have same key/value pair
$b of same type in same order
!== Non- $a !== $b Return TRUE if $a is not identical to $b
Identity
<> Inequality $a <> $b Return TRUE if $a is not equal to $b

9. Type Operators
The type operator instanceof is used to determine whether an object, its parent and its
derived class are the same type or not. Basically, this operator determines which certain class
the object belongs to. It is used in object-oriented programming.

<?php Output:
//class declaration Charu is a developer.
class Developer bool(true)
bool(false)
{}
class Programmer
{}
//creating an object of type Developer
$charu = new Developer();

//testing the type of object

if( $charu instanceof Developer)


{
echo "Charu is a developer.";
} else
{
echo "Charu is a programmer.";
}
echo "</br>";

Educator: Asst. Prof. Twinkle Panchal 18


Unit 1: PHP Fundamentals

var_dump($charu instanceof Developer);


//It will return true.
var_dump($charu instanceof Programmer);
//It will return false.
?>

10. Execution Operators

PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell
command. Execution operator and shell_exec() give the same result.
Operator Name Example Explanation
`` backticks echo Execute the shell command and return the result.
`dir`; Here, it will show the directories available in current
folder.
Note: Note that backticks (``) are not single-quotes.

11. Error Control Operators

PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an
expression, any error message will be ignored that might be generated by that expression.
Operator Name Example Explanation
@ At @file ('non_existent_file') Intentional file error

12. PHP Operators Precedence

Operators Additional Information Associativity

clone new clone and new non-associative

[ array() left

** Arithmetic right

++ -- ~ (int) (float) increment/decrement and right


(string) (array) (object) types
(bool) @
Instanceof Types non-associative

! logical (negation) right

*/% Arithmetic Left

+-. arithmetic and string Left


concatenation
<<>> bitwise (shift) Left

<<= >>= Comparison non-associative

Educator: Asst. Prof. Twinkle Panchal 19


Unit 1: PHP Fundamentals

== != === !== <> Comparison non-associative

& bitwise AND Left

^ bitwise XOR Left

| bitwise OR Left

&& logical AND Left

|| logical OR Left

?: Ternary Left

= += -= *= **= /= .= %= &= Assignment Right


|= ^= <<= >>= =>
And Logical Left

Xor Logical Left


Or Logical Left
, many uses (comma) Left

1.4.2 Conditional Statements

In PHP, conditional statements allow you to execute different blocks of code based on certain
conditions. The most commonly used conditional statements in PHP are `if`, `else`, `elseif`, and
`switch`. Here's an overview of each conditional statement:

1. if statement:
The `if` statement is used to execute a block of code if a specified condition is true.

Syntax

if(condition){
//code to be executed

Example:

$age = 25;

if ($age >= 18) {


echo "You are eligible to vote!";
}

2. if-else statement:
The `if-else` statement allows you to execute one block of code if the condition is true and
another block if the condition is false.

Educator: Asst. Prof. Twinkle Panchal 20


Unit 1: PHP Fundamentals

Syntax :
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}

Example:

$age = 17;

if ($age >= 18) {


echo "You are eligible to vote!";
} else {
echo "You are not eligible to vote yet.";
}

3. elseif statement:
The `elseif` statement provides an alternative condition to check if the previous condition(s)
were false.

Syntax :
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}

Example:

$grade = "B";

if ($grade == "A") {
echo "Excellent!";
} elseif ($grade == "B") {
echo "Good!";
} elseif ($grade == "C") {
echo "Average!";
} else {
echo "Need improvement!";
}

Educator: Asst. Prof. Twinkle Panchal 21


Unit 1: PHP Fundamentals

4 Nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax :
if (condition) {
//code to be executed if condition is true if
(condition) {
//code to be executed if condition is true
}
}

Example :
<?php Output:
$age = 23; Eligible to give vote
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>

4. switch statement:
The `switch` statement is used to select one of many code blocks to be executed, based on the
value of a variable.

Syntax:

switch(expression){
case value1:

//code to be executed

break; case value2:

//code to be executed break;

......
default:

Educator: Asst. Prof. Twinkle Panchal 22


Unit 1: PHP Fundamentals

code to be executed if all cases are not matched;


}

Example:

$day = "Monday";

switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
echo "Midweek";
break;
case "Friday":
echo "End of the week";
break;
default:
echo "Invalid day";
break;
}

Important points to be notice about switch case:


• The default is an optional statement. Even it is not important, that default must always
be the last statement.
• There can be only one default in a switch statement. More than one default may lead to a
Fatal error.
• Each case can have a break statement, which is used to terminate the sequence of
statement.
• The break statement is optional to use in switch. If break is not used, all the statements
will execute after finding matched case value.
• PHP allows you to use number, character, string, as well as functions in switch
expression.
• Nesting of switch statements is allowed, but it makes the program more complex and
less readable.
• semicolon (;) can be used `instead of colon (:). It will not generate any error.

These conditional statements provide the flexibility to make decisions and control the flow of
your PHP code based on different conditions. They allow you to execute specific blocks of code
depending on whether certain conditions are true or false, or based on the value of a variable.

Educator: Asst. Prof. Twinkle Panchal 23


Unit 1: PHP Fundamentals

1.4.3 Arrays

• In PHP, an array is a data structure that can hold multiple values of different data types
in a single variable.
• Arrays can be indexed numerically or associatively, allowing you to access and
manipulate the data easily.
• PHP array is an ordered map (contains value on the basis of key).
• It is used to hold multiple values of similar type in a single variable.

PHP Arrays Types:

1. Numerically Indexed Arrays:


Numerically indexed arrays are arrays where each element is assigned a numeric index
starting from 0.

$fruits = array("apple", "banana", "orange");

//You can also use the shorthand array syntax:

$fruits = ["apple", "banana", "orange"];

// To access individual elements, you can use the index:

echo $fruits[0]; // Output: apple

2. Associative Arrays:
Associative arrays are arrays where each element is assigned a specific key.

$person = array("name" => "John", "age" => 25, "country" => "USA");

// Shorthand syntax:

$person = ["name" => "John", "age" => 25, "country" => "USA"];

// You can access elements using the keys:

echo $person["name"]; // Output: John

3. Multidimensional Arrays:
Multidimensional arrays are arrays that contain other arrays as their elements.

$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// You can access elements using multiple indexes:

echo $matrix[1][2]; // Output: 6

Educator: Asst. Prof. Twinkle Panchal 24


Unit 1: PHP Fundamentals

4. Array Functions:
PHP provides various built-in functions to work with arrays. Some common array functions
include:
1. `count()`: Returns the number of elements in an array.
2. `array_push()`: Adds one or more elements to the end of an array.
3. `array_pop()`: Removes and returns the last element of an array.
4. `array_merge()`: Combines multiple arrays into a single array.
5. `array_key_exists()`: Checks if a specified key exists in an array.

Example usage:

$numbers = [1, 2, 3, 4, 5]; // Output: 5


echo count($numbers);

array_push($numbers, 6); // Output: 6

echo count($numbers);
// Output: 6
$lastNumber = array_pop($numbers);
echo $lastNumber;
// Output: Array ( [0] => apple [1] =>
$fruits = ["apple", "banana"]; banana [2] => orange [3] => grape )
$moreFruits = ["orange", "grape"];
$combinedArray = array_merge($fruits,
$moreFruits);

echo $combinedArray;

if (array_key_exists("name", $person)) {
echo "Name key exists!";
}

Arrays are versatile data structures in PHP, allowing you to store and manipulate collections of
values efficiently. They are widely used in various programming scenarios, such as storing data
retrieved from databases, processing form inputs, or handling complex data structures.

1.5 Sorting Arrays, Php Loops

1.5.1 Sorting Arrays

In PHP, you can sort arrays using various sorting functions and algorithms. Here are some
commonly used methods to sort arrays in PHP:

1. sort():
The `sort()` function sorts an array in ascending order based on its values. The array keys are
reindexed numerically.

$numbers = [4, 2, 1, 3, 5]; Output:


sort($numbers); Array ( [0] => 1 [1] => 2 [2] => 3 [3] =>
print_r($numbers); 4 [4] => 5 )

Educator: Asst. Prof. Twinkle Panchal 25


Unit 1: PHP Fundamentals

2. rsort():
The `rsort()` function sorts an array in descending order based on its values. The array keys
are reindexed numerically.

$numbers = [4, 2, 1, 3, 5]; Output:


rsort($numbers); Array ( [0] => 5 [1] => 4 [2] => 3 [3] =>
print_r($numbers); 2 [4] => 1 )

3. asort():
The `asort()` function sorts an array in ascending order based on its values while maintaining
the association between keys and values.
$fruits = ["orange" => 4, "apple" => 2, Output:
"banana" => 1, "grape" => 3]; Array ( [banana] => 1 [apple] => 2 [grape] =>
asort($fruits); 3 [orange] => 4 )
print_r($fruits);

4. ksort():
The `ksort()` function sorts an array in ascending order based on its keys while maintaining
the association between keys and values.

$fruits = ["orange" => 4, "apple" => 2, Output:


"banana" => 1, "grape" => 3]; Array ( [apple] => 2 [banana] => 1 [grape] =>
ksort($fruits); 3 [orange] => 4 )
print_r($fruits);

5. arsort():
The `arsort()` function sorts an array in descending order based on its values while
maintaining the association between keys and values.

$fruits = ["orange" => 4, "apple" => 2, Output:


"banana" => 1, "grape" => 3]; Array ( [orange] => 4 [grape] => 3 [apple] =>
arsort($fruits); 2 [banana] => 1 )
print_r($fruits);

6. krsort():
The `krsort()` function sorts an array in descending order based on its keys while maintaining
the association between keys and values.

$fruits = ["orange" => 4, "apple" => 2, Output:


"banana" => 1, "grape" => 3]; Array ( [orange] => 4 [grape] => 3 [banana]
krsort($fruits); => 1 [apple] => 2 )
print_r($fruits);

These are some of the commonly used sorting functions in PHP. You can choose the appropriate
function based on your specific sorting requirements and whether you want to sort based on
values or keys, in ascending or descending order.

Educator: Asst. Prof. Twinkle Panchal 26


Unit 1: PHP Fundamentals

1.5.2 PHP Loops

In PHP, loops are used to execute a block of code repeatedly until a specific condition is met.
PHP provides several types of loops to cater to different looping requirements. Here are the
commonly used loop types in PHP:

1. for loop:
The `for` loop is used when the number of iterations are unknown in advance.

Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}

Parameters:

• init counter: Initialize the loop counter value


• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value

Example:

for ($i = 0; $i < 5; $i++) {


echo $i;
}

2. while loop:
The `while` loop is used when you want to execute a block of code as long as a condition is
true.

Syntax :
while (condition is true) {
code to be executed;
}

Example :

$i = 0;
while ($i < 5) {
echo $i;
$i++;
}

3. do-while loop:
The `do-while` loop is similar to the `while` loop, but it executes the block of code at least once
before checking the condition.

Educator: Asst. Prof. Twinkle Panchal 27


Unit 1: PHP Fundamentals

Syntax :
do {
code to be executed;
} while (condition is true);

Example:

$i = 0;
do {
echo $i;
$i++;
} while ($i < 5);

4. foreach loop:
The `foreach` loop is used to iterate over arrays or objects.

Syntax:
foreach ($array as $value) { foreach ($array as $key => $element) {

//code to be executed //code to be executed


}
}

Example 1: Program to print array elements using foreach loop.

$fruits = ["apple", "banana", "orange"]; Output:


foreach ($fruits as $fruit) { apple
echo $fruit; banana
} orange

Example 2: Program to print associative array elements using foreach loop

<?php Output:
//declare array
Name : Alex
$employee = array ( Email : [email protected]
"Name" => "Alex",
Age : 21
"Email" => "[email protected]",
Gender : Male
"Age" => 21,
"Gender" => "Male"
);
// display associative array element
through foreach loop
foreach ($employee as $key => $element)
{
echo $key . " : " . $element;
echo "</br>";

Educator: Asst. Prof. Twinkle Panchal 28


Unit 1: PHP Fundamentals

}
?>

Example 3 : Multi Dimensional Array

<?php Output:
//declare multi-dimensional array
Alex Bob Camila Denial
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";

//display multidimensional array


elements through foreach loop foreach
($a as $e1) { foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>

Example 4: Dynamic array

<?php Output:
//dynamic array php
foreach (array ('p', 'h', 'p’) as $elements)
{
echo "$elements\n";
}
?>

5. break statement:
The `break` statement is used to exit a loop prematurely based on a certain condition.

for ($i = 0; $i < 10; $i++) {


if ($i == 5) {
break;
}
echo $i;
}

Educator: Asst. Prof. Twinkle Panchal 29


Unit 1: PHP Fundamentals

6. continue statement:
The `continue` statement is used to skip the current iteration of a loop and move to the next
iteration.

for ($i = 0; $i < 5; $i++) {


if ($i == 2) {
continue;
}
echo $i;
}

Loops provide a way to automate repetitive tasks and iterate over collections of data. They are
essential for handling scenarios where you need to process a set of data or perform a specific
operation multiple times. The choice of loop type depends on the specific requirements of
program.

Educator: Asst. Prof. Twinkle Panchal 30

You might also like