Basics Of PHP
Introduction to PHP
PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development.
PHP code is executed on the server, and the result is sent to the browser as plain HTML.
PHP statements end with a semicolon ; .
PHP is case-sensitive for variable names but not for keywords.
Variables
Variables declared with $ symbol -> $name = "Anil";
Types are determined automatically (loosely typed).
Variable names must start with a letter or an underscore _.
Data Types
String → "Hello, World!"
Integer → 25
Float → 10.5
Boolean → true or false
Array → ["PHP", "MySQL", "JavaScript"]
Object → Instance of a class
NULL → Represents a variable with no value
Strings Functions
strlen($str) → Returns the length of a string.
str_replace("find", "replace", $str) → Replaces text within a string.
strtolower($str) → Converts to lowercase.
strtoupper($str) → Converts to uppercase.
substr($str, start, length) → Returns a substring.
Arrays
Indexed Array → Uses numeric indexes.
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Output: Red
Associative Array → Uses named keys.
$student = ["name" => "Anil", "age" => 25];
echo $student["name"]; // Output: Anil
Multidimensional Array → Contains multiple arrays.
$users = [
["Anil", 25, "Developer"],
["Sahu", 26, "Designer"]
];
echo $users[0][0]; // Output: Anil
Control Structures
If...Else
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are not an adult.";
}
Switch
$role = "admin";
switch ($role) {
case "admin":
echo "Welcome Admin";
break;
case "editor":
echo "Welcome Editor";
break;
default:
echo "No Access";
}
Loops
For Loop
A for loop is used when the number of iterations is known beforehand.
for ($i = 0; $i < 5; $i++) {
echo $i . " "; // Output: 0 1 2 3 4
}
While Loop
A while loop executes as long as a specified condition is true.
$i = 0;
while ($i < 5) {
echo $i . " ";
$i++;
}
Do...While Loop
do...while checks the condition after executing the loop body at least once.
<?php
$i = 1;
do {
echo "Iteration: $i <br>";
$i++;
} while ($i <= 5);
?>
Foreach Loop
The foreach loop is used to iterate over arrays.
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . " "; // Output: Red Green Blue
}
Use foreach with associative arrays?
<?php
$person = ["name" => "Anil", "age" => 25, "city" => "Delhi"];
foreach ($person as $key => $value) {
echo "$key: $value <br>";
}
?>
Can you break or continue a loop in PHP?
Yes, you can use:
- break to exit the loop entirely.
- continue to skip the current iteration and move to the next.
You can have loops inside other loops.
<?php
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 2; $j++) {
echo "($i, $j) ";
}
echo "<br>";
}
?>
How to iterate a multidimensional array with foreach?
You can nest foreach loops to traverse a multidimensional array.
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
foreach ($matrix as $row) {
foreach ($row as $value) {
echo "$value ";
}
echo "<br>";
}
?>
Comments
Post a Comment