Conditional Statements:
if Statement:
Syntax:
if (condition) {
// Code block executed if condition is true
} elseif (another_condition) {
// Code block executed if another condition is true
} else {
// Code block executed if none of the conditions are true
}
Switch Statement:
Syntax:
switch ($variable) {
case value1:
// Code block executed if $variable equals value1
break;
case value2:
// Code block executed if $variable equals value2
break;
default:
// Code block executed if $variable doesn't match any case
break;
}
Loops:
for Loop:
Syntax:
for ($i = 0; $i < 5; $i++) {
// Code block executed repeatedly until condition is false
}
while Loop:
Syntax:
while (condition) {
// Code block executed repeatedly as long as condition is true
}
do-while Loop:
Syntax:
do {
// Code block executed at least once, then repeatedly as long as condition is true
} while (condition);
foreach Loop:
Syntax:
foreach ($array as $value) {
// Code block executed for each element in $array
}
foreach loop for Associative Array
Syntax
$assocArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
foreach ($assocArray as $key => $value) {
echo "Key: " . $key . ", Value: " . $value . "<br>";
}
Output :
Key: name, Value: John
Key: age, Value: 30
Key: city, Value: New York
Common Functions with Conditionals and Loops: