TY CO PhP Unit 01
TY CO PhP Unit 01
TY CO PhP Unit 01
History of PHP
The history of PHP is quite interesting, reflecting both its growth and the increasing demand
for web development solutions. It started as a small project by Rasmus Lerdorf in 1994 to
track his personal information, and it evolved over time into one of the most widely used
programming languages for web development.
From the humble beginnings of PHP/FI (PHP 2.0) in 1995, PHP has seen substantial
improvements and feature additions in its various versions. Some key milestones include:
PHP 3 (1998) was the first widely used version, marking the start of PHP's rise in
popularity.
PHP 4 (2000) introduced the Zend Engine 1.0, boosting performance and reliability
with new features like object-oriented programming enhancements and COM support.
PHP 5 (2004) was a game-changer with the introduction of Zend Engine II, PDO for
database access, and improved OOP features. This version laid the groundwork for
modern PHP development.
PHP 7 (2015) introduced many improvements like the null coalescing operator, scalar
type declarations, and the spaceship operator (used for comparing values),
significantly improving performance and bringing new capabilities to the language.
PHP comes with a range of both advantages and disadvantages, making it suitable for certain
projects while not ideal for others. Here’s a quick breakdown of the key points:
Advantages of PHP:
1. Speed: PHP can execute quickly, especially when used for web-based applications.
It’s lightweight and doesn’t consume many system resources compared to some other
languages.
2. Ease of Use/Simplicity: The C-like syntax makes it easy for developers with C
programming experience to get up to speed and create websites or web applications.
3. Stability: Given that PHP is supported by a large community of developers, bugs are
often identified and fixed rapidly, leading to a stable development environment.
4. Platform Independence/Portability: PHP can run on multiple platforms like
Windows, Linux, and Mac. This makes it versatile for deployment across different
environments and hosting providers.
5. Open Source: As an open-source language, PHP is free to use, making it accessible
for anyone interested in web development without licensing costs.
6. Built-in Database Connection Modules: PHP has native support for working with
databases, making it ideal for data-driven websites or applications, with seamless
integration for MySQL, Oracle, and more.
7. Powerful Library Support: There’s a wide range of libraries and modules available,
including support for things like PDFs and Graphs, which reduces development time.
8. Flexibility: PHP can be embedded in HTML and easily modified to suit the needs of
developers, offering great flexibility in how web applications are designed and built.
9. Database Connectivity: PHP supports connectivity with several popular database
systems like MySQL, PostgreSQL, and Oracle, enabling it to be used for complex
data-driven applications.
10. Faster Development for Custom Web Applications: PHP is great for rapid
development of custom web applications, allowing developers to implement complex
functionalities quickly.
Disadvantages of PHP:
1. Security: Because it’s open-source, PHP’s code can be accessed and analyzed, which
means vulnerabilities are sometimes exploited more easily. However, the community
actively works on patches and updates.
2. Weak Typing: PHP's implicit type conversions can cause bugs if not carefully
handled. For instance, comparisons between strings like "1000" and "1e3" may lead to
unexpected behavior due to automatic type casting.
3. Not Ideal for Large Web Applications: PHP code can become harder to maintain as
the complexity of the application grows, especially if the code isn’t well-organized. It
also lacks some advanced features that other languages have for large-scale apps.
4. Not Suitable for Desktop Applications: PHP is tailored for web development, not
for building standalone desktop applications, making it a poor choice for that use
case.
5. Modification Limitations: PHP doesn’t allow significant changes to core behavior or
customizations at the system level, which can limit its flexibility in certain situations.
The default file extension for PHP files is "php". A PHP file normally contains HTML tags
and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World” o a web page.
Example: First PHP program.
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Output:
My first PHP page Hello World!
This section is explaining different ways you can embed PHP code into web pages and how
to set up XAMPP, a popular development environment for running PHP scripts locally.
Here’s a breakdown:
1. SGML style:
This is the most common and standard way to embed PHP into an HTML document.
2. ASP style:
This style is rarely used in PHP but is similar to ASP (Active Server Pages) syntax.
3. Script style:
This style is also non-standard, and the script tag is usually used for JavaScript, so
this might lead to issues or be ignored by browsers in modern web development.
XAMPP is a free and open-source cross-platform tool that bundles all the necessary software
to run a local web server, including Apache (web server), MariaDB (database), PHP (for
server-side scripting), and Perl (for server-side scripting).
Steps:
1. Download XAMPP:
Go to the XAMPP website (https://www.apachefriends.org/download.html) and
download the version suitable for your operating system (Windows, macOS, or
Linux).
2. Install XAMPP:
Follow the installation prompts to set up XAMPP on your system.
3. Start Apache Server:
Once installed, open the XAMPP Control Panel. In the control panel, find the
"Apache" section and click on the "Start" button to start the Apache web server. Once
it's running, you'll be able to serve PHP files locally.
4. Creating a PHP File in the htdocs Directory
Now that your Apache server is running on XAMPP, it's time to create your PHP file.
<!DOCTYPE html>
<html>
<body>
<h1>My First PHP Program</h1>
<?php
echo "Hello, World!";
?>
</body>
</html>
4. Save the File: Save the first.php file in the htdocs folder.
5. Access the PHP File:
o Open a web browser and type the following URL in the address bar:
http://localhost/first.php
o You should see a page displaying:
Place your PHP files in the htdocs directory inside the XAMPP installation folder
(e.g., C:\xampp\htdocs\ on Windows).
After placing your PHP file in this directory, you can access it by going to
http://localhost/filename.php in your browser.
2. Variable Variables
PHP allows variable variables, which means a variable’s value can be used as another
variable’s name.
Example:
<?php
$a = "hello";
$$a = "PHP"; // Creates a new variable $hello
A reference means that two variables point to the same memory location.
Example:
<?php
$a = 5;
$b = &$a; // $b is a reference to $a
$b = $b + 2;
echo $a; // Output: 7
?>
Unset Reference
unset($a);
echo $b; // Output: 5
unset($a); removes $a, but $b still retains the last assigned value.
The scope of a variable determines where in the script the variable can be used.
Types of Scope:
1. Local Scope: Variables declared inside a function are only accessible within that
function.
2. Global Scope: Variables declared outside functions can be accessed anywhere using
global keyword.
3. Static Scope: A static variable retains its value between function calls.
4. Function Parameter Scope: Variables used as parameters in functions.
1. Local Scope:
<?php
$a = 4; // Global variable
function assignA() {
$a = 8; // Local variable
echo "a inside function is $a. ";
}
assignA();
echo "a outside of function is $a.";
?>
Output:
vbnet
CopyEdit
a inside function is 8.
a outside of function is 4.
Variables declared outside a function are by default global variables. However, they
cannot be accessed inside a function directly unless you use the global keyword.
<?php
$x = 15; // Global variable
$y = 20; // Global variable
function addition() {
global $x, $y; // Access global variables inside the function
$y = $x + $y; // Modify the global variable
echo "x = $x & y = $y";
}
addition();
?>
Output:
x = 15 & y = 35
Explanation:
A static variable retains its value between multiple function calls. Normally, variables inside
a function get destroyed when the function ends. However, a static variable keeps its value
for future function calls.
<?php
function keep_track() {
static $count = 0; // Declare static variable
$count++; // Increment value
echo $count;
echo "<br>";
}
keep_track(); // Output: 1
keep_track(); // Output: 2
keep_track(); // Output: 3
?>
Explanation:
The static keyword ensures that $count retains its value between function calls.
Each time keep_track() is called, $count increments but does not reset.
Lifetime Exists throughout script execution Retains value between function calls
<?php
// Function to multiply a value by 4
function multiply($value) {
$value = $value * 4; // Multiply by 4
return $value; // Return the result
}
Output:
vbnet
CopyEdit
Return value is 40
Explanation:
PHP provides superglobal variables, which are built-in arrays that are accessible from
anywhere in the script. They hold important information about user input, server details,
cookies, and sessions.
Superglobal Description
Used when data is submitted via a form using the POST method.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Hello, " . $_POST['username']; // Output user input
}
?>
if(isset($_COOKIE["user"])) {
echo "User is " . $_COOKIE["user"];
} else {
echo "No cookie found!";
}
?>
This provides server-related data, such as request methods and script paths.
Conclusion
Function parameters are local to the function and used for passing values.
PHP superglobals ($_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER)
provide important predefined data accessible anywhere in a script.
Example:
$a = 10; // Integer
if (is_int($a)) {
echo "Number is an integer";
}
Floating Point Numbers (Float)
Example:
$x = 3.14;
if (is_float($x)) {
echo "$x is a floating-point number";
}
String
Example:
$a = "Good";
echo "$a, morning \n"; // Expands $a
Output: Good, morning
Boolean
Example:
$x = true;
if (is_bool($x)) {
echo "$x is boolean";
}
Example:
$a = array('A', 'B', 'C'); // Indexed array
$b = array("First" => "A", "Second" => "B", "Third" => "C"); // Associative array
Check if a variable is an array using is_array($var).
Objects
Example:
class Person {
public $name;
function set_name($newname) {
$this->name = $newname;
}
}
$p = new Person();
$p->set_name("Amar");
echo "Hello " . $p->name;
Check if a variable is an object using is_object($var).
Null
Example:
$x = NULL;
if (is_null($x)) {
echo "Variable is NULL";
}
Conclusion
PHP provides a rich set of data types that allow developers to work with various kinds of
data efficiently. Understanding these types is essential for writing clean, efficient, and error-
free PHP code.
PHP Operators
1. Arithmetic Operators
+ Addition -> Sum of $a and $b
- Subtraction -> Difference of $a and $b
* Multiplication -> Product of $a and $b
/ Division -> Quotient of $a and $b (returns float unless both operands are integers)
% Modulus -> Remainder of $a divided by $b
** Exponentiation -> $a raised to the $b'th power (PHP 5.6+)
2. String Concatenation Operator
. Concatenation -> Joins two strings
Example:
$a = "Hello";
$b = " World!";
$c = $a . $b;
echo $c; // Outputs: Hello World!
3. Increment and Decrement Operators
++$a Pre-increment -> Increments $a, then returns it
$a++ Post-increment -> Returns $a, then increments it
--$a Pre-decrement -> Decrements $a, then returns it
$a-- Post-decrement -> Returns $a, then decrements it
4. Comparison Operators
== Equal -> True if $a equals $b after type juggling
=== Identical -> True if $a equals $b and they are of the same type
!= Not equal -> True if $a is not equal to $b
!== Not identical -> True if $a is not equal to $b or not the same type
< Less than -> True if $a is less than $b
> Greater than -> True if $a is greater than $b
<= Less than or equal -> True if $a is less than or equal to $b
>= Greater than or equal -> True if $a is greater than or equal to $b
5. Logical Operators
&&, and -> True if both $a and $b are true
||, or -> True if either $a or $b is true
xor -> True if either $a or $b is true, but not both
!$a -> True if $a is not true
6. Assignment Operators
= Basic assignment -> Assigns value to a variable
+= Add and assign -> $a += $b (same as $a = $a + $b)
-= Subtract and assign -> $a -= $b
*= Multiply and assign -> $a *= $b
/= Divide and assign -> $a /= $b
%= Modulus and assign -> $a %= $b
.= Concatenation assign -> $a .= $b (same as $a = $a . $b)
7. Bitwise Operators
& AND -> Sets bit to 1 if both bits are 1
| OR -> Sets bit to 1 if either bit is 1
^ XOR -> Sets bit to 1 if only one bit is 1
~ NOT -> Flips bits
<< Left shift -> Moves bits left (multiply by 2 for each shift)
>> Right shift -> Moves bits right (divide by 2 for each shift)
8. Type Casting Operators
(int) Integer cast
(float) Float cast
(string) String cast
(bool) Boolean cast
(array) Array cast
(object) Object cast
9. Miscellaneous Operators
@ Error Suppression -> Suppresses error messages
Example:
$result = @file_get_contents("non_existent_file.txt");
`` Execution `` -> Executes shell commands
Example:
$a = 10;
$b = 15;
$max = ($a > $b) ? $a : $b;
echo "Max: $max"; // Outputs: Max: 15
Operator Precedence and Associativity
1. Operator Precedence: Determines the order in which operators are evaluated in an
expression. Higher precedence operators are evaluated before lower precedence ones.
For example, in 1 + 5 * 3, multiplication (*) is evaluated before addition (+), so the
result is 16, not 18.
2. Associativity: Describes how operators of the same precedence level are grouped
when evaluated. It can be:
o Left-to-right (left-associative): Most operators like +, -, and * are left-
associative, meaning expressions are evaluated from left to right.
o Right-to-left (right-associative): Operators like = and ?: are right-associative,
meaning they are evaluated from right to left.
3. Non-associative Operators: Some operators cannot be used next to each other. For
example, 1 < 2 > 1 is illegal in PHP.
Constants in PHP
1. Definition: A constant is a named value that cannot be changed during the script’s
execution. It is declared using the define() function.
2. Syntax:
define("CONSTANT_NAME", value);
Example:
define('PI', 3.14);
echo PI;
Properties:
o Constants are case-sensitive by default, but you can make them case-
insensitive by passing a third argument to define().
o Only scalar values (e.g., integers, strings, floats, booleans) can be used as
constants.
o Constants can be accessed using constant() if the name is dynamic.
1.3.1 if Statement
The if statement executes a block of code if a condition is true.
Syntax:
if (condition) {
// code to execute if true
}
Example:
$x = 11;
if ($x > 10) {
echo "$x is greater than 10";
}
1.3.2 if-else Statement
The if-else statement executes one block of code if the condition is true, and another if it's
false.
Syntax:
if (condition) {
// code if true
} else {
// code if false
}
Example:
$x = 5;
if ($x > 10) {
echo "$x is greater than 10";
} else {
echo "$x is less than 10";
}
if (condition1) {
if (condition2) {
// code
}
}
Example:
$a = 10;
$b = 20;
if ($a == 10) {
if ($b == 20) {
echo "The addition is: " . ($a + $b);
}
}
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
Example:
$var = date("D");
switch ($var) {
case "Sun":
echo "It is Sunday.";
break;
// other cases...
default:
echo "Something wrong";
}
while (condition) {
if (condition) {
break; // exits loop
}
}
Example:
$i = 1;
while ($i <= 10) {
echo $i . " ";
if ($i == 5) break; // Stops at 5
$i++;
}
PHP allows you to execute a block of statements multiple times with loop control structures.
This eliminates the need to write the same code multiple times, making it efficient and more
manageable.
1.4.1 while Loop
The while loop in PHP runs a block of code as long as a specified condition is true.
Syntax:
while(expression) {
// code block to be executed
}
The condition is checked before each iteration.
If true, the code inside the loop executes; if false, the loop stops.
Example:
<?php
$i = 1;
while ($i <= 10) {
echo $i;
$i++;
}
?>
This outputs numbers from 1 to 10.
Alternatively, you can use the while loop with alternative syntax:
<?php
$i = 1;
while ($i <= 10):
echo $i;
$i++;
endwhile;
?>
1.4.2 do while Loop
The do while loop is similar to the while loop but evaluates the condition after executing the
block of code. This guarantees that the code is executed at least once.
Syntax:
do {
// code block to be executed
} while(expression);
Example:
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i <= 10);
?>
1.4.3 for Loop
The for loop is generally used when the number of iterations is known beforehand. It is
shorter and easier to manage than the while loop.
Syntax:
Example:
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
Alternatively, you can use the alternative for syntax:
<?php
for ($i = 1; $i <= 10; $i++):
echo $i;
endfor;
?>
1.4.4 foreach Loop
The foreach loop is used to iterate over arrays. It is only applicable to arrays or objects, and
helps to loop through each element of the array.
Syntax:
Example:
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo $value . " ";
}
?>
This outputs 1 2 3 4.
Expressions
An expression is any valid set of variables, constants, operators, and functions that PHP can
evaluate to produce a value. A simple expression could be as simple as:
Arithmetic Operators
Arithmetic operators perform mathematical operations. PHP automatically converts non-
numeric values to numeric when necessary. Here's a list of arithmetic operators:
+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
This overview should help you get a strong foundation in PHP loops and expressions, making
it easier to write efficient, dynamic scripts.