Menu
Coddy logo textTech

Logical Operators Part 1

Part of the Fundamentals section of Coddy's PHP journey — lesson 25 of 71.

Logical operators let you combine multiple boolean expressions into one. This is essential when you need to check several conditions at once.

The AND operator (&&) returns true only when both conditions are true:

<?php
$age = 25;
$hasLicense = true;

$canDrive = $age >= 18 && $hasLicense;
var_dump($canDrive); // bool(true)

$age = 16;
$canDrive = $age >= 18 && $hasLicense;
var_dump($canDrive); // bool(false) - age condition fails
?>

The OR operator (||) returns true when at least one condition is true:

<?php
$isWeekend = true;
$isHoliday = false;

$dayOff = $isWeekend || $isHoliday;
var_dump($dayOff); // bool(true) - weekend is true

$isWeekend = false;
$dayOff = $isWeekend || $isHoliday;
var_dump($dayOff); // bool(false) - both are false
?>

Think of && as "both must be true" and || as "at least one must be true." In the next lesson, you'll learn about the NOT operator and how to combine multiple logical operators.

challenge icon

Challenge

Easy

Read four values from input: an integer age, a string hasTicket (either "true" or "false"), a string isMember (either "true" or "false"), and a string hasInvitation (either "true" or "false").

Convert the string values to booleans by comparing them to "true".

Evaluate the following two conditions and print the result of each using var_dump(), each on a new line:

  1. Check if the person can enter the event: they must be at least 18 years old AND have a ticket
  2. Check if the person gets free entry: they must be a member OR have an invitation

Example:

If the inputs are 25, true, false, and true, the output should be:

bool(true)
bool(true)

Explanation:

  • 25 >= 18 AND hasTicket is true → true
  • isMember is false OR hasInvitation is true → true

Cheat sheet

The AND operator (&&) returns true only when both conditions are true:

<?php
$age = 25;
$hasLicense = true;

$canDrive = $age >= 18 && $hasLicense;
var_dump($canDrive); // bool(true)
?>

The OR operator (||) returns true when at least one condition is true:

<?php
$isWeekend = true;
$isHoliday = false;

$dayOff = $isWeekend || $isHoliday;
var_dump($dayOff); // bool(true)
?>

Try it yourself

<?php
// Read input values
$age = intval(fgets(STDIN));
$hasTicket = trim(fgets(STDIN));
$isMember = trim(fgets(STDIN));
$hasInvitation = trim(fgets(STDIN));

// TODO: Convert string values to booleans by comparing them to "true"


// TODO: Check if the person can enter the event (at least 18 AND has ticket)


// TODO: Check if the person gets free entry (is member OR has invitation)


// Output the results using var_dump()

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals