Skip to content
Kodivo is live on Product Hunt. Share your review

Conditions and loops explained: how programs make decisions and repeat tasks

A requirement such as “show only available lessons” becomes a condition inside a loop. Follow the values to see how that works.

Turn a rule into a condition

An if statement executes a block when its condition is true. Suppose a lesson is available after completing at least two earlier lessons. That rule needs >=, meaning “greater than or equal to”.

PHP
<?php

$completed = 2;

if ($completed >= 2) {
    echo "Lesson available";
} else {
    echo "Complete another lesson";
}

Output

Lesson available

The program prints Lesson available. The else branch handles a condition that is false. With >, exactly two lessons would not be enough. One word in the requirement affects the operator you choose.

Repeat work with foreach

A loop repeats work. foreach visits the elements of an array. In this standalone script, each title is printed on a separate line:

PHP
<?php

$titles = ["Variables", "Conditions"];

foreach ($titles as $title) {
    echo $title . PHP_EOL;
}

Output

Variables
Conditions

The output is Variables, then Conditions on the next line. Each iteration assigns the next element to $title. For an empty array, the loop body does not run. Displaying an empty-state message requires separate behavior.

Test the boundary

For the first example, check 1, 2 and 3. Each asks a different question: what happens below the threshold, at the threshold and above it? For a list, check no elements and more than one element. Choose cases from the behavior you need.

Distinguish presentation from access control. Hiding a link in the interface does not protect its server address. If a rule needs to restrict access, tell the agent it must also apply to a direct request. The examples here only demonstrate PHP statements.

Ask for a behavior change

Give the agent this task: “Print the array's titles in their existing order. For an empty array, display No lessons yet. Do not modify the input data.” Ask for expected output for both cases, then run the code on your computer.

Kodivo lessons let you follow code and answer a knowledge check. An agent connected through MCP can discuss the material and submit the answer you select. Run your own code variations separately. Find the syntax rules in the if and foreach references.

Kodivo lesson card showing that null differs from false and zero, with PHP code and its output.
The “Null and missing values” sample lesson in Kodivo. Code and output sit beside the explanation.
A Kodivo knowledge check: an isset example with bool(true) and bool(false) answer choices.
In the public demo, you can answer a PHP code question and check your answer. An account saves progress in published lessons.