PHP fundamentals

INDEX
1.1 Concepts of Php and introduction
1.2 Php syntax: variables, constants, echo and print commands
1.3 Data types
1.4 Operators, Conditional Statements (if. Else, Switch. Case), Arrays
1.5 Sorting Arrays, Php Loops
PHP Fundamentals: Introduction and Concepts
✅ What is PHP?
PHP stands for Hypertext Preprocessor.
It is a server-side scripting language primarily used to develop dynamic and interactive websites.
Unlike client-side languages like HTML or JavaScript (which run in the browser), PHP runs on the web server, processes the logic, and sends the result (usually HTML) back to the browser.
✅ History of PHP
PHP was created in 1994 by Rasmus Lerdorf.
Initially, it was a set of Common Gateway Interface (CGI) binaries written in C.
The language has evolved into a powerful and flexible tool used to build everything from simple websites to complex web applications.
PHP is open-source and maintained by a large community.
✅ Why Use PHP?
Here are some reasons why PHP is widely used:
✅ Free and Open Source
✅ Cross-Platform Support (works on Windows, Linux, macOS, etc.)
✅ Easy to Learn for Beginners
✅ Wide Hosting Support
✅ Supports All Major Databases (like MySQL, PostgreSQL, Oracle, etc.)
✅ Large Community & Abundant Resources
✅ Features of PHP
PHP offers a wide range of features that make it a preferred server-side scripting language for web development.
Below is a detailed explanation of each major feature:
1. 🔓 Open Source
Definition: PHP is free to download, use, and modify.
Benefit: Anyone can contribute to its development or customize it to meet their project needs.
Use Case: You can build a website or application without purchasing any licenses.
2. 🌐 Platform Independent (Cross-Platform)
Definition: PHP works on different operating systems like Windows, Linux, macOS, and more.
Benefit: Code written in PHP can be easily deployed on any platform without modification.
Use Case: You can develop on a Windows PC and host the project on a Linux server.
3. 🖥️ Server-Side Scripting
Definition: PHP runs on the server, processes the logic, and sends the final output (usually HTML) to the browser.
Benefit: Keeps source code hidden from users and allows secure data handling.
Use Case: Login systems, contact forms, and eCommerce applications.
4. ⚡ Fast Performance
Definition: PHP is lightweight and executes faster compared to many other scripting languages.
Benefit: Reduces page load time and improves website performance.
Use Case: Real-time web applications such as chat apps or dashboards.
5. 💼 Database Integration
Definition: PHP can easily connect to many types of databases, such as:
MySQL
PostgreSQL
Oracle
SQLite
MongoDB
Benefit: Enables dynamic data handling and storage.
Use Case: Displaying user profiles, handling product listings, managing login credentials.
6. 🔐 Security Features
Definition: PHP provides multiple built-in features to help protect against:
SQL Injection
Cross-Site Scripting (XSS)
Cross-Site Request Forgery (CSRF)
Benefit: Secure data transmission and access control.
Use Case: User authentication systems, payment gateways.
7. 🔄 Easy Integration with HTML, CSS, JavaScript
Definition: PHP code can be embedded directly within HTML.
Benefit: Makes it easy to create dynamic web pages with minimal setup.
Use Case: Dynamically changing content such as user greetings or search results.
8. 🔁 Support for Object-Oriented Programming (OOP)
Definition: PHP supports classes, inheritance, encapsulation, polymorphism, and other OOP principles.
Benefit: Makes code more reusable, manageable, and modular.
Use Case: Building large-scale applications like CRMs, ERPs, or CMS platforms.
9. 🧰 Rich Set of Built-in Functions
Definition: PHP comes with thousands of built-in functions for:
String manipulation
Date/time handling
File operations
Data validation
Benefit: Reduces the need to write code from scratch.
Use Case: File uploads, date formatting, email validation.
10. 🧠 Easy to Learn and Use
Definition: PHP syntax is simple and similar to C, Java, and Perl.
Benefit: Beginners can start quickly without steep learning curves.
Use Case: Teaching web development to students or beginners.
11. 📂 Session Management
Definition: PHP supports handling user sessions and cookies to store data across multiple pages.
Benefit: Enables user login systems, shopping carts, and personalized experiences.
Use Case: Maintaining user state on eCommerce or social media platforms.
12. 📄 File Handling
Definition: PHP can create, read, write, and delete files on the server.
Benefit: Useful for storing logs, creating file uploads/downloads, and generating reports.
Use Case: User uploading documents, generating PDF reports.
13. 🔄 Extensibility and Compatibility
Definition: PHP supports integration with third-party tools, libraries, and frameworks.
Popular Frameworks: Laravel, CodeIgniter, Symfony
Benefit: Enables rapid application development with robust structures.
Use Case: Developing scalable and maintainable enterprise applications.
14. 🤝 Large Community Support
Definition: PHP has a vast developer community and abundant online resources.
Benefit: Easier troubleshooting, access to documentation, and community plugins.
Use Case: New learners can get help through forums, GitHub, Stack Overflow, etc.
15. ⚙️ Support for Web Services and APIs
Definition: PHP can consume or provide REST and SOAP APIs.
Benefit: Allows communication with other platforms and services.
Use Case: Integrating payment gateways, social media login, or third-party apps.
✅ How PHP Works (Execution Flow)
The user sends a request (e.g., clicking a button on a web page).
The request reaches the web server (like Apache or Nginx).
The web server sends the request to the PHP interpreter.
The PHP code is processed on the server, possibly interacting with a database.
The final output (usually HTML) is sent back to the user’s browser.
🔷 1. PHP Syntax Basics
Every PHP script starts with the opening tag
<?php
and ends with?>
.PHP statements are ended with a semicolon (
;
).PHP files are saved with the extension
.php
.
Example:
<?php
// This is a comment
echo “Hello, World!”;
?>
🔷 2. PHP Variables
📌 What is a Variable?
A variable is a container used to store data that can be used and manipulated throughout a PHP program.
📌 Key Rules for PHP Variables:
Must start with a dollar sign (
$
), followed by the name.The variable name must start with a letter or underscore (_).
Variable names are case-sensitive (
$Name
and$name
are different).PHP is a loosely typed language, meaning you don’t need to declare a data type.
✅ Syntax:
$variable_name = value;
✅ Example:
<?php
$name = “Hardik”;
$age = 30;
$price = 99.99;
$isStudent = true;echo $name; // Outputs: Hardik
?>
🔷 3. PHP Constants
📌 What is a Constant?
A constant is a name or identifier for a simple value that cannot be changed during script execution.
📌 Key Features:
Once defined, a constant’s value cannot be changed.
Constants do not start with a
$
sign.Constants are usually written in uppercase letters by convention.
Constants can be global and accessed anywhere in the script.
✅ Syntax to Define a Constant:
define(“CONSTANT_NAME”, value);
✅ Example:
<?php
define(“SITE_NAME”, “TechOneSpot”);
define(“PI”, 3.14);echo SITE_NAME; // Outputs: TechOneSpot
?>
🔷 4. echo
Statement
📌 What is echo
?
echo
is a language construct used to output one or more strings or variables to the browser.It is faster than
print
and is commonly used in PHP.
✅ Key Points:
Can output multiple values, separated by commas.
No return value.
Not used with parentheses (although optional use is allowed).
✅ Syntax:
echo “Message”;
echo “Name: “, $name;
✅ Example:
<?php
$name = “Hardik”;
echo “Welcome “, $name, ” to the PHP course.”;
?>
🔷 5. print
Statement
📌 What is print
?
print
is also a language construct used to display output, similar to echo
. However, print
can only output one argument and it returns 1, so it can be used in expressions.
✅ Key Points:
Slightly slower than
echo
.Returns a value (1), so it can be used in expressions.
Accepts only one string/argument.
✅ Syntax:
print “Message”;
✅ Example:
<?php
$name = “Hardik”;
print “Hello, ” . $name;
?>
🔁 Difference Between echo
and print.
Feature | echo | |
---|---|---|
Parameters | Multiple | Single |
Return Value | No | Yes (returns 1) |
Speed | Slightly faster | Slightly slower |
Use in Expr. | Cannot be used in expression | Can be used in expression |
Preferred For | General output | Simple conditional output |
✅ PHP Fundamentals: Data Types Explained in Detail.
In PHP, data types represent the type of data a variable can hold.
PHP is a loosely typed or dynamically typed language, which means you don’t need to declare a data type explicitly—PHP automatically determines it at runtime based on the value assigned.
🔷 1. String
📌 Description:
A string is a sequence of characters enclosed within single quotes (' '
) or double quotes (" "
). Strings are commonly used to store text.
✅ Example:
<?php
$name = “Hardik”;
$college = ‘SDJ College’;
echo $name;
?>
🧠 Tip:
Double-quoted strings can parse variables inside them, while single-quoted strings cannot.
🔷 2. Integer (int)
📌 Description:
An integer is a whole number without any decimal point. It can be positive or negative.
✅ Example:
<?php
$age = 30;
$score = -100;
echo $age;
?>
🔷 3. Float / Double / Real Numbers
📌 Description:
A float is a number with a decimal point or an exponential form. Also called double or real numbers.
✅ Example:
<?php
$price = 49.99;
$pi = 3.1416;
echo $price;
?>
🔷 4. Boolean
📌 Description:
A boolean data type can only have two possible values: true
or false
. It is often used in conditional logic and decision-making.
✅ Example:
<?php
$isLoggedIn = true;
$isAdmin = false;
echo $isLoggedIn; // Outputs: 1
?>
🔷 5. Array
📌 Description:
An array is a collection of multiple values stored in a single variable. Arrays can be:
Indexed Arrays (with numeric keys)
Associative Arrays (with named keys)
Multidimensional Arrays (arrays within arrays)
✅ Example – Indexed Array:
<?php
$fruits = array(“Apple”, “Banana”, “Mango”);
echo $fruits[1]; // Outputs: Banana
?>
✅ Example – Associative Array:
<?php
$student = array(“name” => “Hardik”, “age” => 22);
echo $student[“name”];
?>
🔷 6. Object
📌 Description:
An object is an instance of a class that can hold data (properties) and functions (methods).
PHP supports Object-Oriented Programming (OOP) using classes and objects.
✅ Example:
<?php
class Student {
public $name = “Hardik”;
function greet() {
return “Hello, ” . $this->name;
}
}$obj = new Student();
echo $obj->greet(); // Outputs: Hello, Hardik
?>
🔷 7. NULL
📌 Description:
A variable is of NULL type if it has no value assigned to it. It represents an empty or non-existent value.
✅ Example:
<?php
$data = NULL;
var_dump($data); // Outputs: NULL
?>
🔷 8. Resource
📌 Description:
A resource is a special data type used to hold a reference to external resources such as database connections, file handles, etc.
✅ Example:
- <?php
$file = fopen(“data.txt”, “r”);
var_dump($file); // Outputs: resource(…)
?>
📊 Summary Table of PHP Data Types:
Data Type | Description | Example |
---|---|---|
String | Text data | "Hello" |
Integer | Whole numbers | 100, -20 |
Float | Decimal numbers | 3.14, 99.99 |
Boolean | True/False values | true, false |
Array | Collection of values | ["red", "green"] |
Object | Instance of a class | $student->name |
NULL | No value | NULL |
Resource | External resource handle | fopen(), mysqli_connect() |
🧠 Final Notes:
PHP automatically detects the data type based on the value.
Use the
gettype()
andvar_dump()
functions to inspect data types.Understanding data types helps in writing more efficient and error-free code.
🔹 1. Arithmetic Operators
Used to perform mathematical operations.
Example :-
<?php
$a = 10;
$b = 3;echo $a + $b; // 13
echo $a – $b; // 7
echo $a * $b; // 30
echo $a / $b; // 3.333…
echo $a % $b; // 1
echo $a ** $b; // 1000 (10^3)
?>
Operator | Description | Example | Output |
---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 4 * 2 | 8 |
/ | Division | 8 / 2 | 4 |
% | Modulus (remainder) | 7 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
🔹 2. Assignment Operators
Used to assign values to variables.
Example :-
<?php
$x = 5;
$x += 3; // 8
$x -= 2; // 6
$x *= 2; // 12
$x /= 3; // 4
$x %= 3; // 1
echo $x;
?>
Operator | Description | Example | Output |
---|---|---|---|
= | Assign value | $x = 10; | 10 |
+= | Add and assign | $x += 5; | x = x + 5 |
-= | Subtract and assign | $x -= 3; | x = x - 3 |
*= | Multiply and assign | $x *= 2; | x = x * 2 |
/= | Divide and assign | $x /= 2; | x = x / 2 |
%= | Modulus and assign | $x %= 3; | x = x % 3 |
🔹 3. Comparison Operators
Used to compare two values. Returns true
or false
.
Example :-
<?php
$a = 5;
$b = “5”;var_dump($a == $b); // true
var_dump($a === $b); // false
var_dump($a != $b); // false
var_dump($a !== $b); // true
var_dump($a > 3); // true
var_dump($a < 10); // true
?>
Operator | Description | Example | Result |
---|---|---|---|
== | Equal (value only) | 5 == "5" | true |
=== | Identical (value + type) | 5 === "5" | false |
!= | Not equal | 4 != 3 | true |
!== | Not identical | 5 !== "5" | true |
> | Greater than | 6 > 2 | true |
< | Less than | 3 < 5 | true |
>= | Greater than or equal to | 5 >= 5 | true |
<= | Less than or equal to | 4 <= 5 | true |
<=> | Spaceship (compare all) | 5 <=> 3 | 1 |
🔹 4. Logical Operators
Used to combine multiple conditions.
Example :-
<?php
$age = 25;
$citizen = true;if ($age >= 18 && $citizen) {
echo “Eligible to vote”;
}if ($age < 18 || !$citizen) {
echo “Not eligible”;
}
?>
Operator | Description | Example | Result |
---|---|---|---|
&& | And (both true) | $x > 3 && $x < 10 | true |
|| | Or (one true) | $x < 5 || $x > 20 | true |
! | Not (reverse result) | !($x == 5) | false |
and | And (low precedence) | $a = true and false; | true (due to precedence) |
or | Or (low precedence) | $a = false or true; | true (due to precedence) |
🔹 5. Increment / Decrement Operators
Used to increase or decrease a value.
Example :-
<?php
$x = 5;echo ++$x; // 6
echo $x++; // 6, then becomes 7
echo –$x; // 6
echo $x–; // 6, then becomes 5
?>
Operator | Description | Example | Result |
---|---|---|---|
++$x | Pre-increment | $x = 5; ++$x; |
6 |
$x++ | Post-increment | $x = 5; $x++; |
5, then 6 |
--$x | Pre-decrement | $x = 5; --$x; |
4 |
$x-- | Post-decrement | $x = 5; $x--; |
5, then 4 |
🔹 6. String Operators
Used to work with text (strings).
Example :-
<?php
$first = “Hello”;
$second = “World”;$full = $first . ” ” . $second;
echo $full; // Hello World$first .= ” Everyone”;
echo $first; // Hello Everyone
?>
Operator | Description | Example | Result |
---|---|---|---|
. | Concatenation | "Hello" . " World" | "Hello World" |
.= | Concatenate & assign | $x = "Hi"; $x .= " there!"; | "Hi there!" |
🔹 7. Array Operators
Used to compare or combine arrays.
Example :-
<?php
$a = [“a” => “Red”, “b” => “Blue”];
$b = [“c” => “Green”, “d” => “Yellow”];$c = $a + $b;
print_r($c); // Union of arraysvar_dump($a == $b); // false
var_dump($a != $b); // true
?>
Operator | Description | Example | Result |
---|---|---|---|
+ | Union | $a + $b | Combines arrays |
== | Equal (same values) | $a == $b | true/false |
=== | Identical (values + order) | $a === $b | true/false |
!= | Not equal | $a != $b | true/false |
!== | Not identical | $a !== $b | true/false |
🔹 8. Type Checking Operators
Used to check the data type of a variable.
Example :-
<?php
$x = “Hello”;if (is_string($x)) {
echo “$x is a string”;
}$y = 25.6;
echo gettype($y); // double
?>
Function | Description | Example |
---|---|---|
is_int() | Checks for integer | is_int(5) → true |
is_string() | Checks for string | is_string("Hi") → true |
is_array() | Checks for array | is_array([1, 2]) → true |
is_bool() | Checks for boolean | is_bool(true) → true |
gettype() | Returns the type | gettype(10) → "integer" |
PHP Conditional Statements.
Conditional statements in PHP allow the program to make decisions based on certain conditions.
These statements control the flow of the program by executing different blocks of code depending on whether a specified condition is true or false.
1. if Statement
The simplest form of a conditional statement. It executes a block of code only if the given condition evaluates to true.
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
$age = 18;
if ($age >= 18) {
echo “You are eligible to vote.”;
}
2. if…else Statement
This allows you to execute one block of code if the condition is true and another block if it is false.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:
$score = 45;
if ($score >= 50) {
echo “You passed the exam.”;
} else {
echo “You failed the exam.”;
}
3. if…elseif…else Statement
Used when there are multiple conditions to check sequentially.
Syntax:
if (condition1) {
// code if condition1 is true
} elseif (condition2) {
// code if condition2 is true
} else {
// code if none of the above conditions are true
}
Example:
$marks = 75;
if ($marks >= 90) {
echo “Grade: A”;
} elseif ($marks >= 75) {
echo “Grade: B”;
} elseif ($marks >= 50) {
echo “Grade: C”;
} else {
echo “Fail”;
}
4. Switch Statement
The switch
statement is an alternative to multiple if...elseif
conditions when checking a variable against different values. It is often cleaner and easier to read.
Syntax:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
default:
// code if none of the cases match
}
Example:
$day = “Monday”;
switch ($day) {
case “Monday”:
echo “Start of the work week.”;
break;
case “Friday”:
echo “Last workday of the week.”;
break;
default:
echo “Midweek days.”;
}
🧮 PHP Fundamentals: Arrays.
In PHP, an array is a data structure that allows you to store multiple values in a single variable.
It is one of the most powerful and flexible types in PHP, used extensively to manage collections of data.
Why Use Arrays?
Imagine you need to store 100 student names. Without arrays, you’d need 100 separate variables.
Arrays allow you to store them all in one place, making your code more efficient and manageable.
🧰 Types of Arrays in PHP
1. Indexed Arrays
These are arrays where each element is assigned a numeric index starting from 0.
Syntax:
$colors = array(“Red”, “Green”, “Blue”);
or (using short syntax):
$colors = [“Red”, “Green”, “Blue”];
Accessing Elements:
echo $colors[0]; // Output: Red
2. Associative Arrays
Here, each element is associated with a custom key (string) instead of a numeric index.
Syntax:
$person = array(“name” => “Hardik”, “age” => 25, “city” => “Surat”);
or:
$person = [“name” => “Hardik”, “age” => 25, “city” => “Surat”];
Accessing Elements:
echo $person[“name”]; // Output: Hardik
3. Multidimensional Arrays
An array containing one or more arrays inside it. It’s useful for representing complex data structures like tables or matrices.
Syntax:
$students = [
[“Hardik”, 90, “A”],
[“Ravi”, 85, “B”],
[“Meena”, 95, “A+”]
];
Accessing Elements
echo $students[0][0]; // Output: Hardik
echo $students[1][1]; // Output: 85
🔍 Array Functions in PHP
PHP offers many built-in functions to work with arrays. Here are some commonly used ones:
Function | Description | Example |
---|---|---|
count() | Counts elements in the array | count($colors) |
array_push() | Adds elements to the end | array_push($colors, "Yellow") |
array_pop() | Removes the last element | array_pop($colors) |
array_merge() | Combines two or more arrays | array_merge($arr1, $arr2) |
in_array() | Checks if a value exists in the array | in_array("Green", $colors) |
array_keys() | Returns all the keys from an array | array_keys($person) |
✅ Example: Associative Array with Loop.
$marks = [“Math” => 80, “Science” => 90, “English” => 85];
foreach ($marks as $subject => $score) {
echo “Subject: $subject – Score: $score<br>”;
}
Output:
Subject: Math – Score: 80
Subject: Science – Score: 90
Subject: English – Score: 85
Important Notes:
Conditions inside
if
orelseif
statements are evaluated as boolean expressions.The
break
statement inside aswitch
is important to stop execution from falling through subsequent cases.PHP supports comparison operators (
==
,===
,!=
,>
,<
, etc.) and logical operators (&&
,||
,!
) inside conditions.
🔢 PHP Fundamentals: Sorting Arrays (Detailed Explanation)
Sorting is the process of arranging data in a specific order.
In PHP, arrays can be sorted by values or keys, either in ascending or descending order.
PHP provides a rich set of functions to handle different types of array sorting.
🧰 Types of Sorting in PHP
1. sort() – Sort Array in Ascending Order (by Values)
This function sorts the elements of an indexed array in ascending order (low to high).
$colors = [“Red”, “Blue”, “Green”];
sort($colors);
print_r($colors);
Output:
Array ( [0] => Blue [1] => Green [2] => Red )
2. rsort() – Sort Array in Descending Order (by Values)
This does the opposite of
sort()
. It sorts an indexed array in descending order.$numbers = [10, 5, 20];
rsort($numbers);
print_r($numbers);
Output:
Array ( [0] => 20 [1] => 10 [2] => 5 )
3. asort() – Sort Associative Array in Ascending Order (by Values)
This maintains the key-value association while sorting by values.
$scores = [“John” => 90, “Alice” => 85, “Bob” => 95];
asort($scores);
print_r($scores);
Output:
Array ( [Alice] => 85 [John] => 90 [Bob] => 95 )
4. arsort() – Sort Associative Array in Descending Order (by Values)
$scores = [“John” => 90, “Alice” => 85, “Bob” => 95];
arsort($scores);
print_r($scores);
Output:
Array ( [Bob] => 95 [John] => 90 [Alice] => 85 )
5. ksort() – Sort Associative Array by Keys (Ascending)
$person = [“name” => “Hardik”, “age” => 25, “city” => “Surat”];
ksort($person);
print_r($person);
Output:
Array ( [age] => 25 [city] => Surat [name] => Hardik )
6. krsort() – Sort Associative Array by Keys (Descending)
$person = [“name” => “Hardik”, “age” => 25, “city” => “Surat”];
krsort($person);
print_r($person);
Output:
Array ( [name] => Hardik [city] => Surat [age] => 25 )
📊 Summary of Sorting Functions.
Function | Sorts by | Order | Keeps Keys? | Use Case |
---|---|---|---|---|
sort() |
Values | Ascending | No | Simple numeric or text arrays |
rsort() |
Values | Descending | No | Reverse value sorting |
asort() |
Values | Ascending | Yes | Maintain keys in associative array |
arsort() |
Values | Descending | Yes | High to low value sort with keys |
ksort() |
Keys | Ascending | Yes | Sort by key alphabetically |
krsort() |
Keys | Descending | Yes | Reverse key alphabetical sort |
✅ Best Practices
Use
asort()
orarsort()
when key-value association matters (like names and marks).Use
ksort()
when sorting based on key names or alphabetical identifiers.Always check the array type before choosing a sorting method.
🔁 PHP Fundamentals: Loops
In PHP, loops are used to execute a block of code repeatedly as long as a certain conditaion is true.
This helps reduce code repetition and makes programs more efficient and concise.
📌 Types of Loops in PHP
PHP provides the following looping structures:
while Loop
do…while Loop
for Loop
foreach Loop
1️⃣ while Loop
🔹 Description:
The while
loop executes a block of code as long as the specified condition is true.
🔹 Syntax:
while (condition) {
// code to execute
}
🔹 Example:
$x = 1;
while ($x <= 5) {
echo “Number: $x <br>”;
$x++;
}
🔹 Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2️⃣ do…while Loop
🔹 Description:
The do...while
loop will always execute the code block once, and then repeat the loop as long as the condition is true.
🔹 Syntax:
do {
// code to execute
} while (condition);
🔹 Example:
$x = 1;
do {
echo “Count: $x <br>”;
$x++;
} while ($x <= 3);
🔹 Output:
Count: 1
Count: 2
Count: 3
3️⃣ for Loop
🔹 Description:
The for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
🔹 Syntax:
for (initialization; condition; increment) {
// code to execute
}
🔹 Example:
for ($i = 1; $i <= 5; $i++) {
echo “Index: $i <br>”;
}
🔹 Output:
Index: 1
Index: 2
Index: 3
Index: 4
Index: 5
4️⃣ foreach Loop
🔹 Description:
The foreach
loop is used to iterate over arrays. It loops through each key/value pair.
🔹 Syntax:
foreach ($array as $value) {
// code to execute
}
Or:
foreach ($array as $key => $value) {
// code to execute
}
🔹 Example:
$colors = [“Red”, “Green”, “Blue”];
foreach ($colors as $color) {
echo “Color: $color <br>”;
}
🔹 Output:
Color: Red
Color: Green
Color: Blue
📊 Summary Table.
Loop Type | Best Use Case | Condition Check | Example Use |
---|---|---|---|
while |
Unknown number of iterations beforehand | Start | Input validation |
do...while |
Run at least once, then check condition | End | Login retry logic |
for |
Known number of iterations | Start | Counted loops |
foreach |
Iterating through arrays or collections | Internal | Looping through arrays |
✅ Tips:
Use
break
to exit a loop early.Use
continue
to skip the current iteration.Always make sure your loop condition eventually becomes false to avoid infinite loops.
✅ Summary
Concept | Description | Example |
---|---|---|
Variable | Stores data; starts with $ | $name = "Hardik"; |
Constant | A fixed value that cannot be changed | define("SITE", "MySite"); |
echo | Outputs data; faster, allows multiple values | echo "Hello", $name; |
Outputs one value; returns 1, can be used in expressions | print "Welcome"; |
Arrays store multiple values in a single variable.
PHP supports indexed, associative, and multidimensional arrays.
Arrays can be traversed using loops and manipulated using many built-in functions.