Unit 1
Unit 1
History of PHP
PHP (Hypertext Preprocessor) was created in 1994 by Rasmus Lerdorf. Initially, it was a set of Common Gateway
Interface (CGI) scripts for tracking visits to his online resume. Over time, it evolved into a full-fledged scripting
language. The language underwent several iterations, with PHP 5 introducing object-oriented programming, and
later versions adding performance improvements and new features.
Advantages of PHP
1. Open Source: PHP is free to use and has a large, active community.
2. Cross-Platform: PHP works on various operating systems like Windows, Linux, and macOS.
3. Ease of Use: PHP has a simple syntax similar to C, making it easy to learn.
4. Integration: PHP integrates seamlessly with databases like MySQL, and web servers like Apache.
5. Wide Adoption: Many popular platforms like WordPress and Magento are built on PHP.
Syntax of PHP
PHP syntax is straightforward, and every PHP script starts with <?php and ends with ?>. Statements in PHP end
with a semicolon ;. PHP is embedded within HTML, allowing dynamic content generation.
Basic Example:
<?php
/*
*/
// Declaring variables
$name = "Alice";
$age = 25;
// Printing output
?>
1.2 Variables, Data types, Expressions and operators, constants
1. Variables
Variables in PHP are used to store data and must start with a $ symbol. They can contain letters, numbers, and
underscores but must not start with a number.
Syntax:
$variable_name = value;
Example:
<?php
$name = "John"; // String
$age = 25; // Integer
$height = 5.9; // Float
$isStudent = true; // Boolean
echo "Name: $name, Age: $age, Height: $height, Is Student: $isStudent";
?>
2. Data Types
PHP supports the following data types:
1. String: Sequence of characters enclosed in quotes.
2. Integer: Whole numbers.
3. Float: Decimal numbers.
4. Boolean: true or false.
5. Array: Collection of values.
6. Object: Instance of a class.
7. Null: Special data type with no value.
Example:
<?php
$greeting = "Hello, PHP!";
$year = 2024;
$temperature = 36.5;
$isRaining = false;
$colors = ["Red", "Green", "Blue"];
$unknown = null;
echo $greeting;
?>
3. Expressions
Expressions in PHP are combinations of variables, values, and operators that produce a result.
Example:
<?php
$x = 10;
$y = 20;
$result = $x + $y; // Expression: $x + $y
echo "Result: $result"; // Outputs: Result: 30
?>
4. Operators
Operators are used to perform operations on variables and values.
Types of Operators:
1. Arithmetic Operators: +, -, *, /, %
2. Assignment Operators: =, +=, -=, *=, /=
3. Comparison Operators: ==, !=, <, >, <=, >=
4. Logical Operators: &&, ||, !
5. String Operators: . (concatenation), .= (concatenation assignment)
Example:
<?php
$a = 15;
$b = 5;
$sum = $a + $b;
echo "Sum: $sum"; // Outputs: 20
$isEqual = ($a == $b);
echo "Equal: $isEqual"; // Outputs:
$isBothTrue = ($a > 10 && $b < 10);
echo "Both Conditions Met: $isBothTrue"; // Outputs: 1 (true)
?>
5. Constants
Constants are like variables, but once defined, their value cannot be changed. Use the define() function or const
keyword.
Syntax:
define("CONSTANT_NAME", value);
Example:
<?php
define("PI", 3.14);
define("GREETING", "Welcome to PHP");
echo "Value of PI: " . PI; // Outputs: 3.14
echo "Message: " . GREETING; // Outputs: Welcome to PHP
?>
2. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
<?php
$marks = 75;
if ($marks >= 50) {
echo "You passed the exam.";
} else {
echo "You failed the exam.";
}
?>
3. Nested if Statement
A nested if is an if statement inside another if statement, allowing multiple levels of conditions.
Syntax:
if (condition1) {
if (condition2) {
// Code if both conditions are true
}}
Example:
<?php
$age = 25;
$hasID = true;
if ($age >= 18) {
if ($hasID) {
echo "You can enter the club.";
} else {
echo "You need an ID to enter.";
}
} else {
echo "You are too young to enter.";
}?>
4. break Statement
The break statement terminates the current loop or switch case.
Example:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Stops the loop when $i equals 5
}
echo $i . " ";
}
?>
5. switch Statement
The switch statement evaluates an expression and matches it to one of several cases.
Syntax:
switch (expression) {
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Code if no case matches
}
Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week.";
break;
case "Friday":
echo "End of the work week.";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "Invalid day.";
}
?>
6. continue Statement
The continue statement skips the current iteration of a loop and moves to the next one.
Example:
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skips even numbers
}
echo $i . " ";
}
?>
Effect Terminates the loop or switch immediately Skips to the next iteration of the loop
Use Case Exit from loops or switch cases entirely Skip specific iterations in loops
Summary
• if, if-else, and nested if allow conditional execution of code.
• switch simplifies decision-making with multiple cases.
• break exits loops or switch cases prematurely.
• continue skips specific iterations in loops without terminating them.
These statements form the backbone of decision-making in PHP programs.
1.4 Loop control structures-while, while, for and foreach
1. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition) {
// Code to be executed
}
Example:
<?php
$i = 1;
while ($i <= 5) {
echo "Count: $i<br>";
$i++;
}?>
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
2. do-while Loop
The do-while loop executes the code block at least once, then repeats the loop as long as the condition is true.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
<?php
$i = 1;
do {
echo "Count: $i<br>";
$i++;
} while ($i <= 5);
?>
3. for Loop
The for loop is used when the number of iterations is known. It contains an initializer, a condition, and an
increment/decrement in a single line.
Syntax: for (initializer; condition; increment/decrement) {
// Code to be executed}
Example:
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i<br>";
}?>
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
4. foreach Loop
The foreach loop is specifically designed for iterating through arrays. It operates on each element of an array
without needing an index.
Syntax:
foreach ($array as $value) {
// Code to be executed
}
Example (Simple Array): Example (Associative Array):
<?php <?php
$fruits = ["Apple", "Banana", "Cherry"]; $student = ["Name" => "John", "Age" => 20,
"Grade" => "A"];
foreach ($fruits as $fruit) {
foreach ($student as $key => $value) {
echo "Fruit: $fruit<br>";
echo "$key: $value<br>";
}?>
}?>
Output:
Output:
Fruit: Apple
Name: John
Fruit: Banana
Age: 20
Fruit: Cherry
Grade: A
Key Differences Between Loops
do-while Use when the block must execute at least once. Yes
Summary
1. while: Repeats as long as the condition is true.
2. do-while: Executes once, then checks the condition.
3. for: Suitable for loops with a defined number of iterations.
4. foreach: Ideal for traversing arrays effortlessly.
By selecting the appropriate loop structure, you can write efficient and readable PHP code.