UNIT1 PHP
UNIT1 PHP
What is PHP?
PHP stands for Hypertext Preprocessor (though it originally meant Personal Home Page). PHP was primarily
created by Rasmus Lerdorf, a Danish-Canadian programmer It's a widely-used open-source scripting language
specifically designed for web development. This means it's free to use and relatively easy to learn compared
to other programming languages
History of PHP
PHP's journey began in the early 1990s with Rasmus Lerdorf, a Danish-Canadian programmer. Here's a
glimpse into its evolution:
1993-1994: Lerdorf creates a set of Common Gateway Interface (CGI) scripts in C to manage his personal
website.
1995: Lerdorf expands these scripts to include functionalities like tracking visitors and guestbooks. He
releases it as "Personal Home Page Tools" (PHP Tools).
1995: A major rewrite happens, and it's christened "Personal Home Page/Forms Interpreter" (PHP/FI). This
version boasts a more advanced scripting interface.
1997: With growing popularity, a team effort led by Zeev Suraski and Andi Gutmans rewrites the PHP/FI
parser, forming the base for PHP Version 3. This version is considered much closer to the PHP we know
today.
1998: Work begins on a complete overhaul of PHP's core by Andi Gutmans and Zeev Suraski.
2004: PHP 5 is released after extensive development. It introduces significant improvements in performance,
object-oriented programming features, and error handling.
Present: PHP continues to evolve with new features and versions being released regularly. The focus remains
on enhancing performance, security, and integration with modern frameworks.
Variable in php
Variables in PHP are like containers that hold information you can use throughout code. They allow to store and
manipulate data of various types.
Declaring Variables:
Use a dollar sign ($) followed by the variable name.
Variable names can contain letters, numbers, and underscores, but must start with a letter or underscore.
PHP is case-sensitive, so $name and $NAME are considered different variables.
Example:
$firstName = "John";
$age = 30;
$isStudent = true;
Constants in PHP
Constants in PHP are essentially fixed values that, unlike variables, cannot be changed after they are defined during
script execution. They provide a way to represent values that should remain consistent throughout code.
Constants are created using either the define() function or the const keyword (introduced in PHP 5.3).
Expressions
Expressions in PHP are the fundamental building blocks of your code. They are any combination of values, variables,
operators, and function calls that can be evaluated to produce a single value
Conditional statements
Conditional statements in PHP are fundamental constructs that allow your code to make decisions and execute different
blocks of code based on specific conditions. They are essential for creating dynamic and interactive programs.
1. if statement:
Checks a single condition.
If the condition is true, the code block within the if statement executes.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
2. if-else statement:
Checks a single condition.
If the condition is true, the code block within the if statement executes.
If the condition is false, the code block within the else statement executes (optional).
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
$grade = "B";
if ($grade == "A") {
echo "Excellent work!";
} else {
echo "Keep practicing!";
}
3. if-elseif-else statement:
Checks multiple conditions one by one.
If the first condition is true, its corresponding code block executes, and the rest are skipped.
If the first condition is false, it checks the second elseif condition (optional), and so on.
If none of the conditions are true, the optional else block executes.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if all conditions are false
}
Example:
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} else {
echo "Grade: C";
}
4. switch statement:
Evaluates an expression against a list of values.
If a match is found, the corresponding code block executes.
It's useful for handling multiple conditions that check for the same variable against different values.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
default:
// Code to execute if no match is found (optional)
}
Example:
$day = "Monday";
switch ($day) {
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "It's a weekday.";
}
Looping statements
PHP provides several looping statements to execute a block of code repeatedly. Here's a breakdown of the common
ones:
1.for Loop:
Ideal when you know the exact number of iterations beforehand.
Syntax:
for ($initialization; $condition; $increment/decrement) {
// Code to be executed
}
Exampe:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
2.while Loop:
Executes the code block as long as a specified condition is true.
Syntax:
while ($condition) {
// Code to be executed
}
Exampe:
$input = "";
while ($input !== 'q') {
$input = readline("Enter 'q' to quit: ");
if ($input !== 'q') {
echo "You entered: $input\n";
}
}
3. do-while Loop:
Similar to while loop, but the code block executes at least once even if the condition is initially false.
Syntax:
do {
// Code to be executed
} while ($condition);
Exampe:
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
4.foreach Loop:
Specifically designed to iterate over arrays or similar data structures.
Syntax :
foreach ($array as $value) {
echo $value . " ";
}
Exampe:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
2.Integer
An integer data type is a non-decimal number
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
Example
$x = 5985;
var_dump($x);
3.Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
Example
$x = 10.365;
var_dump($x);
4.Boolean
A Boolean represents two possible states: TRUE or FALSE.
Example
$x = true;
var_dump($x);
5. Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
Example
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
How it Works:
The expression ($variable) is evaluated.
If the expression evaluates to null, the ?? operator assigns the $default_value to the result ($result).
If the expression evaluates to a non-null value (including 0, false, an empty string, or any other value), that value is
directly assigned to the result ($result).
Example:
$name = null;
$greeting = "Hello, " . ($name ?? "Guest") ."!";
echo $greeting; // Output: Hello, Guest!
Keywords
In PHP, keywords are special words that have a predefined meaning and function within the programming language.
These keywords cannot be used for other purposes like variable names or function names. They are the building blocks
that define the structure and functionality of your PHP code.
Purpose: Define statements, control flow, functions, and other core aspects of code.
Examples: if, else, for, while, function, class, echo, print.
Cannot be used as: Variable names, function names, or constants (except for some special cases).
Understanding keywords is essential for writing valid and efficient PHP code
Operators
In PHP, operators are special symbols that perform operations on values (operands) to produce a new result. They are
essential for manipulating data, performing calculations, making comparisons, and controlling the flow of code.
1. Arithmetic Operators:
Perform basic mathematical operations like addition, subtraction, multiplication, division, etc.
Examples: +, -, *, /, % (modulus - remainder after division)
2. Comparison Operators:
Used to compare values and return a boolean (true/false) result.
Examples: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or
equal to)
3. Logical Operators:
Combine conditions to create more complex logical expressions.
Examples: && (AND - both conditions must be true), || (OR - at least one condition must be true), ! (NOT - inverts the
truth value)
4. Assignment Operators:
Assign values to variables, sometimes combined with other operations.
Examples: = (simple assignment), += (add and assign), -= (subtract and assign), *= (multiply and assign), etc.
5. Increment/Decrement Operators:
Increase or decrease the value of a variable by 1.
Examples: ++ (pre-increment - increment before use), -- (pre-decrement - decrement before use), $x++ (post-increment
- use the value and then increment), $x-- (post-decrement - use the value and then decrement