Control Structures
$OK = true;
$OK = FalSe;
PHP considers all of the following false
false
and null
<?php
if (condition is true) {
do something
}
<?php
if (condition is true) {
do something
} else {
do something else
}
<?php
if (condition is true) {
do something
} elseif {
perform alternative task
} else {
do something different
}
Symbol | Meaning |
---|---|
== | Both values are equal |
!= | Values are not equal |
=== | Values are identical |
!== | Values are not identical |
> | Value on the left is greater than the one on the right |
>= | Value on the left is greater than or equal to the one on the right |
< | Value on the right is greater than the one on the left |
<= | Value on the right is greater than or equal to the one on the left |
<?php
switch ($var) {
case 'value1':
// do something
break;
case 'value2':
// do something different
break;
default:
// do something else
}
<?php
while (condition) {
// code to be executed
}
<?php
// initialize value
$i = 1;
while ($i < 10) {
echo $i . '
';
// increment $i
$i++;
}
<?php
do {
// code to be executed
} while (condition)
<?php
// initialize value
$i = 100;
do {
echo $i . '
';
// increment $i
$i++;
} while ($i <= 10;)
<?php
for (initialize; condition; increment) {
// code to be executed
}
<?php
$characters = ['Bugs','Daffy','Speedy'];
for ($i = 0; $i < count($characters); $i++) {
echo $characters[$i] . '
';
}
Let's build a list of characters in HTML!
<?php
foreach ($array_name as $value) {
// do something with $value
}
<?php
$characters = ['Bugs','Daffy','Speedy'];
foreach ($characters as $item) {
echo $item . '
';
}
<?php
foreach ($array_name as $key => $value) {
// do something with $key and $value
}
<?php
$descriptions = [
'Bugs' => 'bunny',
'Daffy' => 'duck',
'Speedy' => 'the fastest mouse'
];
foreach ($descriptions as $key => $description) {
echo "$key is $description
";
}
Try It!
<?php
foreach ($descriptions as $key => $description) {
echo "$key is";
if ($key !== 'Speedy') echo ' a';
echo "" $description
";
}
PHP has many built in functions.
<?php
function f_name($parameters) {
// do something
}
<?php
function double_value($my_number) {
return $my_number * 2;
}
$i = 2;
echo double_value($i); // 4
<?php
include 'some_folder/some_file.php';
<?php
include 'includes/functions.php';