<?php
$color = null;
$weather = 'sunny';
// using if-elseif-else
if ($weather == 'sunny') {
$color = 'blue';
} elseif ($weather == 'cloudy') {
$color = 'grey';
} else {
$color = 'error: invalid weather';
}
echo $color . PHP_EOL;
// using switch-case
switch ($weather) {
case 'sunny':
$color = 'blue';
break;
case 'cloudy':
$color = 'grey';
break;
default:
$color = 'error: invalid weather';
break;
}
echo $color . PHP_EOL;
// using switch-case with expression
switch (true) {
case $weather == 'sunny':
$color = 'blue';
break;
case $weather == 'cloudy':
$color = 'grey';
break;
default:
$color = 'error: invalid weather';
break;
}
echo $color . PHP_EOL;
// using match
match ($weather) {
'sunny' => $color = 'blue',
'cloudy' => $color = 'grey',
default => $color = 'error: invalid weather',
};
echo $color . PHP_EOL;
// using match to return a value
$color = match ($weather) {
'sunny' => 'blue',
'cloudy' => 'grey',
default => 'error: invalid weather',
};
echo $color . PHP_EOL;
// using an associative array
$colors = [
'sunny' => 'blue',
'cloudy' => 'grey',
];
echo ($colors[$weather] ?? 'error: invalid weather') . PHP_EOL;
To embed this project on your website, copy the following code and paste it into your website's HTML: