In the realm of web development, PHP stands as a powerful language that empowers developers to create dynamic and interactive web pages. At the heart of this dynamism lie PHP statements, which are the fundamental instructions that dictate how a PHP script executes. These statements guide various actions, from displaying content to making decisions and performing repetitive tasks. Let’s delve into the key types of PHP statements, accompanied by illustrative code examples.
1. Output Statements:
- echo and print: These serve the purpose of displaying content to the web page.
echo "Welcome to PHP!";
print "Hello, world!";
2. Conditional Statements:
- if, else if, else: These statements enable decision-making within your code, executing specific blocks based on conditions.
$age = 25;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not yet eligible to vote.";
}
3. Loops:
- while, do-while, for, foreach: These statements facilitate the repetition of code blocks, often used for iterating through arrays or performing tasks multiple times.
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $number) {
echo $number . " ";
}
4. Function Calls:
- Functions: These are reusable blocks of code that can be called upon to perform specific tasks.
function greet($name) {
echo "Hello, $name!";
}
greet("Alice"); // Output: Hello, Alice!
5. Variable Assignment:
- Assignment operator (=): Used to store values in variables for later use.
$name = "John Doe";
$age = 30;
6. Arithmetic Operators:
- *+, -, , /, %: Perform mathematical operations on numbers.
$result = 10 + 5; // $result will be 15
7. Comparison Operators:
- ==, !=, <, >, <=, >=: Compare values and return true or false.
if ($age >= 18) {
// Code to execute if condition is true
}
8. Logical Operators:
- && (and), || (or), ! (not): Combine multiple conditions for complex decision-making.
if ($age >= 18 && $hasLicense) {
// Code to execute if both conditions are true
}
9. Control Flow Statements:
- break, continue, return: Modify the flow of code execution within loops and functions.
foreach ($items as $item) {
if ($item === "apple") {
break; // Exit the loop immediately
}
}
10. Comments:
- // (single-line), /**/ (multi-line): Add non-executable notes within code for clarity and documentation.
// This is a single-line comment
/* This is a multi-line comment */