Example 7: Number Traversal

for Loops and conditional search in PHP

Download file recorrido_numeros

🎯 Live Demo

Traversal from 0 to the 10

0
1
2
3
4
5
🎯
6
7
8
9
10
Numbers traversed: 11
Target searched: 5
Times found: 1

Search different numbers!

We will search for this number in the range 0-10

Quick searches:

🔍 Search simulation:

📖 Code Explanation

Complete PHP Code

<?php
for ($i = 0; $i <= 10; $i++) {
    if ($i == 5) {
        print($i);
    }
}
?>

📝 Line 1: Loop for

for ($i = 0; $i <= 10; $i++) {

What does it do? Creates a loop that runs 11 times, from 0 to 10.

Why is it done this way? for loop is ideal when we know exactly how many times we need to repeat the code.

💡 Concept: Anatomy of the loop for

Initialization: $i = 0 - Initial value
Condition: $i <= 10 - While it's true
Increment: $i++ - Increases by 1 each cycle

📝 Lines 2-4: Condition if

if ($i == 5) {
print($i);
}

What does it do? Checks if the current number equals 5 and, if so, prints it.

Why is it done this way? Combines a loop with a condition to search for specific elements.

💡 Concept: Linear search

This is a simple example of linear search: we check each element one by one until we find the target.

📝 Step-by-step execution flow

1
Initialization: $i = 0
2
Check: ¿$i <= 10?
3
Execution: Loop body (condition if)
4
Increment: $i++
5
Repetition: Go back to step 2 until the condition is false

🔄 Types of Loops in PHP

Loop for

for ($i = 0; $i < 10; $i++) {
    // código
}

✅ Ideal for:

  • Known number of iterations
  • Traverse arrays by index
  • Counters and sequences

Loop while

$i = 0;
while ($i < 10) {
    // código
    $i++;
}

✅ Ideal for:

  • Complex conditions
  • Unknown number of iterations
  • Reading files/BD

Loop foreach

foreach ($array as $valor) {
    // código
}

✅ Ideal for:

  • Traverse arrays and objects
  • You don't need the index
  • Cleaner code

➕ Increment Operators/Decrement

Operator Name Example Result
$i++ Post-increment $a = $i++; $a = original value, then $i increases
++$i Pre-increment $a = ++$i; $i increases, then $a = new value
$i-- Post-decrement $a = $i--; $a = original value, then $i decreases
--$i Pre-decrement $a = --$i; $i decreases, then $a = new value

🎯 Common Loop Patterns

Linear search

foreach ($array as $elemento) {
    if ($elemento == $objetivo) {
        echo "Found!";
        break;
    }
}

Traverse a collection until finding an element.

Accumulation

$suma = 0;
for ($i = 1; $i <= 10; $i++) {
    $suma += $i;
}

Accumulate values during the traversal.

Filtering

$pares = [];
foreach ($numeros as $num) {
    if ($num % 2 == 0) {
        $pares[] = $num;
    }
}

Create a new collection with elements that meet a condition.

🎯 Key Concepts Learned

Loop for

  • Ideal for counted iterations
  • Three parts: start, condition, increment
  • Very efficient for indexed arrays
  • Full control over the counter

Conditions in loops

  • Can use break to exit early
  • Can use continue to skip an iteration
  • Combine logic with repetition
  • Essential for searches

Counter variables

  • $i is the convention for indices
  • Must be initialized before the loop
  • Modified on each iteration
  • Controls the loop's end

💪 Practical Exercise

Extend the search system

Practice these changes to improve your skills:

  1. Modify the code to search for multiple numbers at once
  2. Implement a counter that shows how many numbers are even in the range
  3. Create a system that searches for prime numbers in the range 0-20
  4. Convert the loop for to while and vice versa to practice
  5. Add the ability to search custom ranges (e.g.: 5-15)

Solution 1: Multiple targets

<?php
$objetivos = [2, 5, 8];
$encontrados = [];

for ($i = 0; $i <= 10; $i++) {
    if (in_array($i, $objetivos)) {
        $encontrados[] = $i;
    }
}

print_r($encontrados);
?>

Solution 2: Even number counter

<?php
$pares = 0;
for ($i = 0; $i <= 10; $i++) {
    if ($i % 2 == 0) {
        $pares++;
    }
}

echo "Números pares: \$pares";
?>

Solution 3: Prime numbers

<?php
$primos = [];
for ($i = 2; $i <= 20; $i++) {
    $esPrimo = true;
    for ($j = 2; $j < $i; $j++) {
        if ($i % $j == 0) {
            $esPrimo = false;
            break;
        }
    }
    if ($esPrimo) {
        $primos[] = $i;
    }
}

print_r($primos);
?>

Solution 4: With while

<?php
$i = 0;
while ($i <= 10) {
    if ($i == 5) {
        echo $i;
    }
    $i++;
}
?>

Solution 5: Custom range

<?php
$inicio = 5;
$fin = 15;
$objetivo = 10;

for ($i = $inicio; $i <= $fin; $i++) {
    if ($i == $objetivo) {
        echo "Encontrado: \$i";
        break;
    }
}
?>