1_PHP
1_PHP
• 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.
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.
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.
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.
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!";
?>
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
These are implemented using script tags. This syntax is removed in PHP 7.0.0. So it’s no more
used.
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";
%>
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:
3. Variable Scope:
• PHP variables have different scopes that define their accessibility.
• 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:
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();
?>
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.
function testLocalScope() {
$localVar = 20;
echo $localVar;
}
testLocalScope(); // Outputs: 20
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`:
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
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;
?>
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.
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.
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:
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");
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:
Constant() function
There is another way to print the value of constants using constant() function instead of
using the echo statement.
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
throughout the code. By convention, constants are often used for configuration settings, system
values, or other unchanging data.
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:
<?php Output:
echo "Hello, World!";
?> Hello, World!
<?php Output:
$name = " Ram Chandra "; Hello, Ram Chandra!
echo "Hello, " . $name . "!";
?>
- 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>";
?>
<?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:
<?php Output:
print "Hello, World!"; Hello, World!
?>
<?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";
?>
<?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>";
?>
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.
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
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!"`
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.
$isTrue = true;
$isFalse = false;
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]`
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;
}
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();
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.
- Example: (Resource)
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.
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.
2. Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment
operator is "=".
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.
~ 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:
!== 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
5. Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.
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.
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:
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
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();
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.
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
[ array() left
** Arithmetic right
| bitwise OR Left
|| logical OR Left
?: Ternary Left
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;
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.
Syntax :
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Example:
$age = 17;
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!";
}
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
......
default:
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;
}
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.
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.
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"];
3. Multidimensional Arrays:
Multidimensional arrays are arrays that contain other arrays as their elements.
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
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:
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.
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.
2. rsort():
The `rsort()` function sorts an array in descending order based on its values. The array keys
are reindexed numerically.
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.
5. arsort():
The `arsort()` function sorts an array in descending order based on its values while
maintaining the association between keys and values.
6. krsort():
The `krsort()` function sorts an array in descending order based on its keys while maintaining
the association between keys and values.
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.
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:
Example:
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.
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) {
<?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>";
}
?>
<?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";
<?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.
6. continue statement:
The `continue` statement is used to skip the current iteration of a loop and move to the next
iteration.
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.