← PHP tutorial

PHP

Conditionals

if, elseif, and else work the same as most C-family languages, each block wrapped in curly braces, condition in parentheses.

Example: a time-of-day greeting

<?php
  $hour = 14;

  if ($hour < 12) {
    echo "Good morning";
  } elseif ($hour < 18) {
    echo "Good afternoon";
  } else {
    echo "Good evening";
  }
?>
Good afternoon

Note the spelling: PHP uses elseif as one word (though else if as two words also works), a small but real difference from JavaScript's else if, worth knowing so it doesn't trip you up switching between languages.

Example
<?php
  $hour = 14;

  if ($hour < 12) {
    echo "Good morning";
  } elseif ($hour < 18) {
    echo "Good afternoon";
  } else {
    echo "Good evening";
  }
?>
Output
Good afternoon
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Backend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account