Unit I PHP
Unit I PHP
What is PHP?
History of PHP
PHP was introduced by Rasmus Lerdorf in 1994, the first version and participated in
the later versions. It is an interpreted language and it does not require a compiler. The
language quickly evolved and was given the name “PHP,” which initially named was
“Personal Home Page.”
• PHP 3 (1998): The first version considered suitable for widespread use.
• PHP 4 (2000): Improved performance and the introduction of the Zend Engine.
Characteristics of PHP
• It can be integrated with many databases such as Oracle, Microsoft SQL Server.
• It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others.
• One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.
Syntax
<?php
?>
Basic Example of PHP
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Output:
Features of PHP
• Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.
• Database Integration: PHP provides built-in support for interacting with databases,
such as MySQL, PostgreSQL, and others.
• Server-Side Scripting: PHP scripts are executed on the server, generating HTML that
is sent to the client’s browser.
Applications of PHP
PHP is versatile and can be used in a variety of web development scenarios, including:
• Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.
• Content Management Systems (CMS): Many popular CMSs like WordPress, Joomla,
and Drupal are built with PHP.
• E-commerce Platforms: PHP is commonly used to develop e-commerce websites due
to its database integration capabilities.
• Web Applications: PHP is used for creating feature-rich web applications such as
social media platforms, forums, and customer relationship management (CRM)
systems.
• API Development: PHP can be used to create APIs for web and mobile applications.
Advantages of PHP
• Easy to Learn: The syntax of PHP is quite similar to C and other programming
languages. This makes PHP relatively easy to learn, especially for developers who
already have some programming experience.
• Database Support: PHP has excellent support for various databases, including
MySQL, PostgreSQL, SQLite, and more. This makes it easy to connect and interact
with databases, a crucial aspect of many web applications.
• Server-Side Scripting: PHP scripts are executed on the server, reducing the load on
the client’s side. This server-side scripting capability is crucial for generating dynamic
content and performing server-related tasks.
Disadvantages of PHP
• Security Concerns: If not handled properly, PHP code may be susceptible to security
vulnerabilities, such as SQL injection and cross-site scripting (XSS). Developers need
to be cautious and follow best practices to secure PHP applications.
• Performance: While PHP performs well for many web applications, it may not be as
fast as some compiled languages like C or Java. However, advancements and
optimizations in recent versions have improved performance.
• Lack of Modern Features: Compared to newer languages, PHP may lack some
modern language features. However, recent versions of PHP have introduced
improvements and features to address this concern.
• Limited OOP’S Support: Although PHP supports OOP, its implementation has been
criticized for not being as robust as in some other languages. However, recent
versions have introduced improvements to enhance OOP capabilities.
Essential Of PHP
Variables:
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
o As PHP is a loosely typed language, so we do not need to declare the data types of
the variables. It automatically analyzes the values and makes conversions to its
correct datatype.
$variablename=value;
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
Example :
<?php
$str="hello string";
$x=200;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
?>
Output:
The scope of a variable is defined as its range in the program under which it can be
accessed. In other words, "The scope of a variable is the portion of the program within
which it is defined and can be accessed."
1. Local variable
2. Global variable
3. Static variable
Local variable
Local variables are declared inside a function or method and are only accessible
within that function. They do not exist outside the function's scope.
Example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
Global variable
Global variables are declared outside of any function and can be accessed from
anywhere in the script. You need to use the global keyword inside a function to modify a
global variable.
Example:
<?php
$name = "Ram"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Static variable
Static variables are local variables that retain their values between function calls.
They are initialized only once when the function is first called.
Example:
<?php
function static_var()
{
static $num1 = 3; //static variable
$num1++;
static_var();
?>
Output:
Static: 4
PHP data types are used to hold different types of data or values. PHP supports 8
primitive data types that can be categorized further in 3 types:
3. Special Types
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
1. resource
2. NULL
Integer (int):
The integer data type represents whole numbers, both positive and negative,
without a fractional or decimal component.
String:
The string data type represents sequences of characters, such as text. Strings can be
enclosed in single quotes (') or double quotes (").
Boolean (bool):
Boolean data types represent one of two possible values: true or false. Booleans are
often used for conditional statements and comparisons.
Comments:
PHP Operators
Operators are used to performing operations on some values. In other words, we can
describe operators as something that takes some values, performs some operation on
them, and gives a result.
• Arithmetic Operators
• Comparison Operators
• Array Operators
• Increment/Decrement Operators
• String Operators
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their
syntax and operations in PHP.
+ Addition $x + $y
– Subtraction $x – $y
* Multiplication $x * $y
/ Division $x / $y
** Exponentiation $x ** $y
% Modulus $x % $y
Example:
<?php
$x = 10;
$y = 3;
// Addition
// Subtraction
// Multiplication
// Division
// Exponentiation
// Modulus
?>
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1
These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or
cannot be met so the result of a conditional statement can either be true or false. Here are
the logical operators along with their syntax and operations in PHP.
Operator Name Syntax
or Logical OR $x or $y
Example:
<?php
$x = 50;
$y = 30;
if ($x == 50 or $y == 20)
Output:
and Success
or Success
xor Success
Comparison Operators:
These operators are used to compare two elements and outputs the result in
boolean form. Here are the comparison operators along with their syntax and operations in
PHP.
Operator Name Syntax
== Equal To $x == $y
!= Not Equal To $x != $y
Example:
<?php
$a = 80;
$b = 50;
$c = "80";
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
These operators are used to compare two values and take either of the results
simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used
as a shorthand notation for if…else statement that we will read in the article on decision
making.
Syntax:
Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.
If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted
otherwise the result is on right.
Example:
<?php
$x = -12;
?>
Output:
Assignment Operators:
These operators are used to assign values to different variables, with or without mid-
operations. Here are the assignment operators along with their syntax and operations, that
PHP provides for the operations.
= Assign $x = $y
Example:
<?php
$y = 75;
echo $y, "<br>";
$y = 100;
$y += 200;
$y = 70;
$y -= 10;
$y = 30;
$y *= 20;
$y = 100;
$y /= 5;
$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0
Array Operators:
These operators are used in the case of arrays. Here are the array operators along
with their syntax and operations, that PHP provides for the array operation.
!== Non-Identity $x !== $y Returns True if both are not identical to each other
Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are
used to increment or decrement values.
This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.
Example:
<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
$x .= $y . $z;
echo $x;
?>
Output:
GeeksforGeeks!!!
GeeksforGeeks!!!
PHP allows us to perform actions based on some type of conditions that may be
logical or comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an
action would be performed as asked by the user.
• if statement
• if…else statement
• if…elseif…else statement
• switch statement
if Statement:
If statement is used to executes the block of code exist inside the if statement only if
the specified condition is true.
Syntax
if(condition){
//code to be executed }
Example
<?php
$num=12;
if($num<100){
?>
Output:
If-else Statement
If-else statement is slightly different from if statement. It executes one block of code
if the specified condition is true and another block of code if the condition is false.
Syntax
if(condition){
}else{
Example
<?php
$num=12;
if($num%2==0){
}else{
?>
Output:
12 is even number
If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements.
So, we can check multiple conditions using this statement.
Syntax
if (condition1){
} elseif (condition2){
} else{
<?php
$x = "August";
if ($x == "January") {
else{
?>
Output:
Switch Statement:
The switch statement is used to select one of many code blocks to be executed.
Syntax :
switch (expression)
break;
break; //
Additional cases...
}
Example:
<?php
$n = "February";
switch($n) {
case "January":
break;
case "February":
break;
case "March":
break;
default:
?>
Output:
Its February
PHP Loops
1. While Loop:
The while loop repeatedly executes a block of code as long as a specified condition is
true.
Syntax :
while (condition) {
}
Example :
<?php
$count = 1;
$count++;
?>
Output :
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
The do-while loop is very similar to the while loop, the only difference is that the do-
while loop checks the expression (condition) at the end of each iteration.
Syntax:
do {
// Code is executed
Example :
<?php
$num = 10;
do
$num += 2;
} while ($num < 20);
?>
Output
10
12
14
16
18
3. for Loop:
Syntax :
Example :
<?php
?>
Output :
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
3. foreach Loop:
The foreach loop is used to iterate over elements in an array or other iterable
objects.
Syntax :
Example :
<?php
?>
Output:
I like apple
I like banana
I like cherry
PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP
supports only 256-character set and so that it does not offer native Unicode support. There
are 4 ways to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest
way to specify string in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a
literal backslash (\) use double backslash (\\).
Example
<?php
echo $str;
?>
Output:
Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But
escape sequences and variables will be interpreted using double quote PHP strings.
Example
<?php
echo $str;
?>
Output:
Now, you can't use double quote directly inside double quoted string.
Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an
identifier is provided after this heredoc <<< operator, and immediately a new line is started
to write any text. To close the quotation, the string follows itself and then again that same
identifier is provided.
Example
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing identifier
echo $str;
?>
Output:
It is a valid example
Nowdoc :
Nowdoc is very much similar to the heredoc other than the parsing done in
heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by an
identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc.
Example:
<?php
$str = <<<'DEMO'
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str.
Demo;
?>
Output:
This function takes a string as argument and returns and integer value representing
the length of string. It calculates the length of the string including all the whitespaces and
special characters.
Syntax
strlen( $string )
<?php
$len = strlen($str);
?>
Output
String Length: 24
Syntax
<?php
$count = str_word_count($str);
Output
Word Counr: 3
Syntax
<?php
echo strrev($str);
?>
Output
skeeGrofskeeG ot emocleW
The strtoupper() function takes a string as argument and returns the string with all
characters in Upper Case.
Syntax
strtoupper( $string )
<?php
$str = "geeksforgeeks";
$upperCase = strtoupper($str);
echo $upperCase;
?>
Output
GEEKSFORGEEKS
5. PHP strtolower() Function
This function takes a string as argument and returns the string with all of the
characters in Lower Case.
Syntax
strtolower( $string )
<?php
$str = "GEEKSFORGEEKS";
$lowerCase = strtolower($str);
echo $lowerCase;
?>
Output
geeksforgeeks
This function takes a string as argument and returns the string with the first character
in Upper Case and all other cases of the characters remains unchanged.
Syntax
ucfirst( $string )
Example: Convert the first letter of string to upper case using ucfirst() function.
<?php
$firstUpper = ucfirst($str);
echo $firstUpper;
?>
Output
Welcome to geeksforgeeks
7. PHP lcfirst() Function
This function takes a string as argument and returns the string with the first character
in Lower Case and all other characters remains unchanged.
Syntax
lcfirst( $string )
Example: Convert the first letter string to lower case using lcfirst() function.
<?php
$firstLower = lcfirst($str);
echo $firstLower;
?>
Output
wELCOME to GeeksforGeeks
This function takes a string as argument and returns the string with the first character
of every word in Upper Case and all other characters remains unchanged.
Syntax
ucwords( $string )
Example: Convert the first letter of each words to uppercase using ucwords() function.
<?php
$firstUpper = ucwords($str);
echo $firstUpper;
?>
Output
Welcome To Geeksforgeeks
PHP Arrays
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.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP index is represented by number which starts from 0. We can store number,
string and object in the PHP array. All PHP array elements are assigned to an index number
by default.
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example:
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
We can associate name with each array elements in PHP using => symbol.
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example:
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
?>
Output :
PHP multidimensional array is also known as array of arrays. It allows you to store
tabular data in an array. PHP multidimensional array can be represented in the form of
matrix which is represented by row * column.
Example :
$emp = array
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);