Skip to main content

Course Progress

Loading...

PHP While Loops - Control Structures

Duration: 30 minutes
Module 2: Loops in PHP

Learning Objectives

  • Master PHP loop structures
  • Choose appropriate loop types
  • Control loop execution flow
  • Optimize loop performance

Introduction to PHP While Loops

Welcome to our session on PHP While Loops, a fundamental control structure that every PHP developer should master. While loops provide a flexible way to execute a block of code repeatedly as long as a specified condition remains true.

Think of a while loop as a security guard who keeps checking if a door is locked – as long as the door remains unlocked (the condition is true), the guard continues checking and performing their duties. Once the door becomes locked (the condition becomes false), the guard moves on to the next task.

Diagram
True False >|True| C[Execute Code Block] C >|False| E[Exit Loop] E Start Execute Code Block Update Condition State Exit Loop Continue Program Test Condition

Unlike for loops, which are typically used when you know exactly how many iterations you'll need, while loops shine when the number of iterations is undetermined or depends on conditions that may change during execution.

Basic Syntax of PHP While Loops

The while loop in PHP follows a straightforward syntax:

while (condition) {
    // code to be executed
    // update condition state (important!)
}
  • Condition: An expression that evaluates to either true or false
  • Code Block: The statements to be executed as long as the condition is true
  • Update Condition State: Usually includes code that will eventually change the condition to false

Think of the while loop as a ticket checker at an amusement park ride – as long as there are people in line (condition is true), the checker continues to verify tickets (execute code). When no one is left in line (condition becomes false), the checker stops and moves on.

Example: Basic While Loop

<?php
// Print numbers from 1 to 5 using a while loop
$i = 1;
while ($i <= 5) {
    echo "Number: $i <br>";
    $i++; // Don't forget this, or the loop will run indefinitely!
}
?>

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

In this example, we initialize $i = 1 before the loop begins. The condition $i <= 5 keeps the loop running as long as $i is less than or equal to 5. Inside the loop, we increment $i with $i++, which is crucial to eventually make the condition false and prevent an infinite loop.

How While Loops Execute

Let's dive deeper into how a while loop executes:

  1. First, the condition is evaluated.
  2. If the condition is true, the code inside the loop executes.
  3. After executing the code, control returns to step 1, and the condition is evaluated again.
  4. This process repeats until the condition evaluates to false.
  5. When the condition becomes false, the loop terminates, and program execution continues with the code after the loop.
Start Condition Check: Is condition true? Execute Code Exit Loop False True Return to condition check

A key point to remember is that in a while loop, the condition is checked before the code block executes. This means that if the condition is false to begin with, the code inside the loop will never execute – not even once.

Think of a while loop as a bouncer at a club – they check IDs (the condition) before letting anyone in (executing the code). If someone doesn't meet the criteria, they don't get in at all.

Variations and Techniques

Pre-test vs. Post-test Loops

The standard while loop is a "pre-test" loop, meaning it tests the condition before executing the loop body. PHP also offers a "post-test" loop called do-while, which we'll cover in our next session.

Diagram
True False True False >|True| C1[Execute Code] C1 Start Execute Code Exit Start Execute Code Exit Test Condition Test Condition

The key difference: a while loop might execute zero times if the condition is initially false, whereas a do-while loop always executes at least once because the condition is checked after the first execution.

Using Multiple Conditions

While loops can contain complex conditions using logical operators:

<?php
// Loop until either $a reaches 10 or $b reaches 20
$a = 0;
$b = 0;

while ($a < 10 && $b < 20) {
    echo "a: $a, b: $b <br>";
    $a += rand(0, 2); // Increase by 0, 1, or 2
    $b += rand(0, 3); // Increase by 0, 1, 2, or 3
}

echo "Final values - a: $a, b: $b";
?>

Sample Output:

a: 0, b: 0
a: 2, b: 1
a: 3, b: 3
a: 5, b: 6
a: 6, b: 7
a: 8, b: 9
a: 10, b: 12
Final values - a: 10, b: 12

This example continues looping until either $a reaches 10 or $b reaches 20, whichever happens first. It's like having two alarm clocks – the loop continues until either one goes off.

Dynamic Condition Modification

One of the powerful aspects of while loops is that the condition can be dynamically modified by code inside or outside the loop:

<?php
// User input simulation
$userInputs = ["apple", "banana", "quit", "orange", "grape"];
$currentInput = 0;

// Process until user enters "quit"
while ($currentInput < count($userInputs) && $userInputs[$currentInput] != "quit") {
    echo "Processing: " . $userInputs[$currentInput] . "<br>";
    $currentInput++;
}

echo "Program terminated after processing " . $currentInput . " inputs.";
?>

Output:

Processing: apple
Processing: banana
Program terminated after processing 2 inputs.

This simulates processing user inputs until a quit command is received. Think of it as a receptionist answering phone calls until it's time to go home – the stopping condition depends on external factors.

Practical Applications

File Processing

While loops are excellent for processing files where you don't know how many lines you'll need to read:

<?php
// Reading a file line by line
$file = fopen("data.txt", "r");

if ($file) {
    // Read until end of file
    while (!feof($file)) {
        $line = fgets($file);
        // Skip empty lines
        if (trim($line) !== '') {
            echo "Line: " . htmlspecialchars($line) . "<br>";
        }
    }
    fclose($file);
} else {
    echo "Unable to open file!";
}
?>

This code reads a file line by line until it reaches the end. It's like a scanner going through a document – it keeps processing until there's nothing left to scan.

When to Use:

Use while loops when processing files, especially large ones, as you generally don't know how many lines you'll need to read in advance.

Database Query Results

While loops are commonly used to process database query results:

<?php
// Example with mysqli
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);

if ($result) {
    echo "<table border='1'>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
    
    // Fetch rows until there are no more
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['name'] . "</td>";
        echo "<td>" . $row['email'] . "</td>";
        echo "</tr>";
    }
    
    echo "</table>";
    $result->free();
} else {
    echo "Error: " . $mysqli->error;
}

$mysqli->close();
?>

This pattern is particularly useful because fetch_assoc() returns false when no more rows are available, elegantly terminating the loop. It's like an assembly line worker processing items as they come down the conveyor belt until the belt is empty.

User Input Validation

While loops can be used to repeatedly prompt for input until valid data is received:

<?php
// Simulating command-line input with a web example
$validInput = false;
$attempts = 0;
$maxAttempts = 3;
$inputs = ["", "abc", "42", "invalid"];  // Simulation of user inputs

while (!$validInput && $attempts < $maxAttempts) {
    // In a real CLI application, you'd use readline() or similar
    $input = $inputs[$attempts];
    $attempts++;
    
    echo "Attempt $attempts - Input: '$input'<br>";
    
    // Validate: must be a number between 1 and 100
    if (is_numeric($input) && $input >= 1 && $input <= 100) {
        $validInput = true;
        echo "Valid input received: $input<br>";
    } else {
        echo "Invalid input. Please enter a number between 1 and 100.<br>";
    }
}

if (!$validInput) {
    echo "Maximum attempts reached. Please try again later.";
}
?>

Output:

Attempt 1 - Input: ''
Invalid input. Please enter a number between 1 and 100.
Attempt 2 - Input: 'abc'
Invalid input. Please enter a number between 1 and 100.
Attempt 3 - Input: '42'
Valid input received: 42

This approach is like a patient teacher who keeps asking a question until they get a correct answer, but only up to a certain point before moving on.

Performance Considerations

Diagram
> C[Move Constants Outside] A While Loop Performance Evaluate Condition Once Move Constants Outside Avoid Resource-Intensive Operations Consider Alternative Structures

While loops can be efficient, but improper implementation might lead to performance issues. Here are some key considerations:

  • Condition evaluation: The condition is evaluated on every iteration, so make it as simple and efficient as possible.
  • Resource handling: When working with resources (files, database connections), ensure they're properly opened before the loop and closed after the loop.
  • Loop termination: Always ensure there's a clear path for the loop to terminate, avoiding infinite loops.
  • Alternative structures: Sometimes, a for loop or foreach loop might be more appropriate and efficient.

Inefficient vs. Efficient While Loop

Inefficient:

<?php
// Inefficient - complex condition evaluated each time
$i = 0;
while ($i < count($largeArray) && strtotime("now") < $endTime) {
    // Process $largeArray[$i]
    $i++;
}
?>

Efficient:

<?php
// Efficient - pre-calculate array size
$i = 0;
$size = count($largeArray);
$timeLimit = $endTime;
while ($i < $size && time() < $timeLimit) {
    // Process $largeArray[$i]
    $i++;
}
?>

The efficient version reduces repeated function calls in the condition, making each iteration faster. It's like planning your grocery shopping route before you start rather than deciding where to go at each aisle.

Real-World Examples

Implementing a Rate Limiter

While loops can be used to implement simple rate limiters or throttling mechanisms:

<?php
// Simple API rate limiter simulation
function callExternalApi($data) {
    // Simulate API call
    echo "API call with data: " . json_encode($data) . "<br>";
    return ["status" => "success", "message" => "Data processed"];
}

$apiRequests = [
    ["user" => "user1", "action" => "update"],
    ["user" => "user2", "action" => "create"],
    ["user" => "user3", "action" => "delete"],
    ["user" => "user4", "action" => "read"],
    ["user" => "user5", "action" => "update"],
];

$requestsPerSecond = 2; // Maximum 2 requests per second
$i = 0;

while ($i < count($apiRequests)) {
    $batchStart = microtime(true);
    $batchCount = 0;
    
    // Process up to $requestsPerSecond requests in this batch
    while ($i < count($apiRequests) && $batchCount < $requestsPerSecond) {
        $result = callExternalApi($apiRequests[$i]);
        $i++;
        $batchCount++;
    }
    
    // Calculate time spent on this batch
    $batchTime = microtime(true) - $batchStart;
    
    // If we processed quickly, wait until 1 second has passed
    if ($batchTime < 1 && $i < count($apiRequests)) {
        $waitTime = 1 - $batchTime;
        echo "Rate limiting: waiting " . number_format($waitTime, 2) . " seconds...<br>";
        // In a real application, you would use sleep() or usleep()
        // sleep($waitTime); // Uncomment in real usage
    }
}

echo "All API requests completed.";
?>

Output:

API call with data: {"user":"user1","action":"update"}
API call with data: {"user":"user2","action":"create"}
Rate limiting: waiting 0.98 seconds...
API call with data: {"user":"user3","action":"delete"}
API call with data: {"user":"user4","action":"read"}
Rate limiting: waiting 0.99 seconds...
API call with data: {"user":"user5","action":"update"}
All API requests completed.

This rate limiter ensures we don't overwhelm an external API by limiting requests to a certain number per second. It's like pacing yourself during a long-distance run – going too fast at the beginning will deplete your energy too quickly.

Web Crawler/Scraper

While loops are ideal for web crawlers that need to process an unknown number of pages:

<?php
// Simple web crawler simulation
function getLinksFromPage($url) {
    // In a real crawler, this would parse HTML and extract links
    // Here we're just simulating with fixed data
    $pageData = [
        "https://example.com/" => [
            "https://example.com/about",
            "https://example.com/products"
        ],
        "https://example.com/about" => [
            "https://example.com/team",
            "https://example.com/history"
        ],
        "https://example.com/products" => [
            "https://example.com/products/1",
            "https://example.com/products/2"
        ],
        // Other pages have no outgoing links
        "https://example.com/team" => [],
        "https://example.com/history" => [],
        "https://example.com/products/1" => [],
        "https://example.com/products/2" => []
    ];
    
    echo "Crawling: $url<br>";
    return isset($pageData[$url]) ? $pageData[$url] : [];
}

// Initialize with starting URL
$startUrl = "https://example.com/";
$urlsToVisit = [$startUrl];
$visitedUrls = [];
$maxPages = 10; // Safety limit
$pagesVisited = 0;

// Continue until no more URLs or we hit the limit
while (!empty($urlsToVisit) && $pagesVisited < $maxPages) {
    // Get the next URL to process
    $currentUrl = array_shift($urlsToVisit);
    
    // Skip if already visited
    if (in_array($currentUrl, $visitedUrls)) {
        continue;
    }
    
    // Add to visited set
    $visitedUrls[] = $currentUrl;
    $pagesVisited++;
    
    // Get links from this page
    $links = getLinksFromPage($currentUrl);
    
    // Add new links to our queue
    foreach ($links as $link) {
        if (!in_array($link, $visitedUrls) && !in_array($link, $urlsToVisit)) {
            $urlsToVisit[] = $link;
        }
    }
}

echo "Crawler finished after visiting $pagesVisited pages.";
?>

Output:

Crawling: https://example.com/
Crawling: https://example.com/about
Crawling: https://example.com/products
Crawling: https://example.com/team
Crawling: https://example.com/history
Crawling: https://example.com/products/1
Crawling: https://example.com/products/2
Crawler finished after visiting 7 pages.

This crawler keeps visiting new URLs as long as there are unvisited links and we haven't reached our limit. It's like exploring a maze where you discover new passages as you go, and you won't know how many turns you'll take until you've finished exploring.

Common Patterns and Use Cases

Reading Until End of Input

A classic while loop pattern is reading data until there's no more input:

<?php
// CSV file processing example
function processCSV($filename) {
    $handle = fopen($filename, "r");
    $headerProcessed = false;
    $headers = [];
    $data = [];
    
    if ($handle) {
        while (($line = fgetcsv($handle)) !== FALSE) {
            if (!$headerProcessed) {
                // First line contains headers
                $headers = $line;
                $headerProcessed = true;
            } else {
                // Associate data with headers
                $rowData = [];
                foreach ($headers as $index => $header) {
                    if (isset($line[$index])) {
                        $rowData[$header] = $line[$index];
                    } else {
                        $rowData[$header] = null;
                    }
                }
                $data[] = $rowData;
            }
        }
        fclose($handle);
    }
    
    return $data;
}

// Simulated usage
$fileData = [
    ["Name", "Age", "Email"],
    ["John Doe", "30", "john@example.com"],
    ["Jane Smith", "25", "jane@example.com"],
    ["Bob Johnson", "45", "bob@example.com"]
];

// Simulate CSV file
$tempFile = tmpfile();
foreach ($fileData as $row) {
    fputcsv($tempFile, $row);
}
rewind($tempFile);

// Get the temporary filename
$metaData = stream_get_meta_data($tempFile);
$tempFilename = $metaData['uri'];

// Process the CSV
$result = processCSV($tempFilename);

// Display the processed data
echo "<pre>";
print_r($result);
echo "</pre>";

// Close the temporary file
fclose($tempFile);
?>

Output:

Array
(
    [0] => Array
        (
            [Name] => John Doe
            [Age] => 30
            [Email] => john@example.com
        )
    [1] => Array
        (
            [Name] => Jane Smith
            [Age] => 25
            [Email] => jane@example.com
        )
    [2] => Array
        (
            [Name] => Bob Johnson
            [Age] => 45
            [Email] => bob@example.com
        )
)

This pattern processes data from a source that signals the end of input (in this case, when fgetcsv() returns FALSE). It's like reading a book until you reach the last page – you don't know in advance how many pages you'll read.

Retry Logic

While loops are perfect for implementing retry logic for operations that might temporarily fail:

<?php
// Retry pattern for unreliable operation
function performUnreliableOperation() {
    // Simulate an operation that sometimes fails
    $success = (rand(0, 3) > 0); // 75% success rate
    
    if ($success) {
        echo "Operation succeeded!<br>";
        return true;
    } else {
        echo "Operation failed!<br>";
        return false;
    }
}

$maxRetries = 5;
$retryCount = 0;
$success = false;

// Try the operation until success or max retries
while (!$success && $retryCount < $maxRetries) {
    echo "Attempt " . ($retryCount + 1) . ": ";
    $success = performUnreliableOperation();
    
    if (!$success) {
        $retryCount++;
        
        if ($retryCount < $maxRetries) {
            $waitTime = pow(2, $retryCount); // Exponential backoff
            echo "Retrying in $waitTime seconds...<br>";
            // In a real application, you would use sleep($waitTime)
        }
    }
}

if ($success) {
    echo "Task completed successfully after " . ($retryCount + 1) . " attempt(s).";
} else {
    echo "Task failed after $maxRetries attempts. Giving up.";
}
?>

Sample Output:

Attempt 1: Operation failed!
Retrying in 2 seconds...
Attempt 2: Operation failed!
Retrying in 4 seconds...
Attempt 3: Operation succeeded!
Task completed successfully after 3 attempt(s).

This retry pattern with exponential backoff is like a persistent salesperson who keeps trying to call a client, but waits longer between each attempt to avoid being annoying.

Best Practices and Pitfalls

Diagram
> C[Initialize Variables Before Loop] A > E[Use Appropriate Loop Type] B > B2[Consider adding safety limits] C > D1[Modify condition variables reliably] E > E2[For: Known range] E While Loop Best Practices Ensure Loop Termination Initialize Variables Before Loop Update Condition Variables Inside Loop Use Appropriate Loop Type Always have a clear exit condition Consider adding safety limits Set initial states outside loop Modify condition variables reliably While: Unknown number of iterations For: Known range Foreach: Collection traversal

Best Practices

  • Initialize variables before the loop: Always set up your variables before entering the while loop.
  • Ensure loop termination: Make sure there's always a way for the condition to become false.
  • Safety limits: Consider adding maximum iteration limits to prevent runaway loops, especially with user input or external data.
  • Clear condition updates: Make sure the code that updates the condition variables is clearly visible and reliable.
  • Use the right loop: Choose while loops when the number of iterations is unknown in advance.

Common Pitfalls

Infinite Loops

The most common error with while loops is creating an infinite loop:

<?php
// INCORRECT: Infinite loop - condition never becomes false
$counter = 1;
while ($counter > 0) {
    echo "This is iteration $counter<br>";
    $counter++; // This will never make $counter <= 0
}
?>

Since $counter starts positive and keeps increasing, it will never become zero or negative, resulting in an infinite loop.

An infinite loop is like a hamster running on a wheel – it keeps going and going without ever reaching a destination.

Missing Condition Updates

Another common mistake is forgetting to update the condition variables:

<?php
// INCORRECT: Forgot to update the loop counter
$i = 0;
while ($i < 5) {
    echo "Iteration: $i<br>";
    // Oops, forgot $i++
}
?>

This loop will execute the first iteration and then get stuck because $i is never incremented.

Condition Logic Errors

Using incorrect logical operators in conditions can cause unexpected behavior:

<?php
// INCORRECT: Logic error in condition
$a = 5;
$b = 10;

// Intended to run while either $a or $b is positive
while ($a > 0 || $b > 0) {
    echo "a: $a, b: $b<br>";
    $a--;
    
    // Oops, we forgot to decrement $b
    // Even after $a reaches 0, $b keeps the loop running
}
?>

In this example, we intended to exit the loop when both variables reach zero, but since we're using OR (||) instead of AND (&&), the loop continues as long as either variable is positive, and we never decrement $b.

Advanced Techniques

Nested While Loops

Like for loops, while loops can be nested to handle multi-dimensional data or complex algorithms:

<?php
// Generate a simple triangular pattern
$i = 1;
while ($i <= 5) {
    $j = 1;
    while ($j <= $i) {
        echo $j . " ";
        $j++;
    }
    echo "<br>";
    $i++;
}
?>

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

Nested while loops function similarly to nested for loops. They're useful when dealing with hierarchical data or when the number of iterations for both the inner and outer loops is undetermined.

Using Break and Continue

The break and continue statements can control the flow of while loops:

<?php
// Process a list of numbers, skipping negatives and stopping at zero
$numbers = [7, 3, -2, 5, 0, 8, 4];
$i = 0;

while ($i < count($numbers)) {
    $num = $numbers[$i];
    $i++;
    
    // Skip negative numbers
    if ($num < 0) {
        echo "Skipping negative number: $num<br>";
        continue;
    }
    
    // Stop if we hit zero
    if ($num == 0) {
        echo "Found zero, stopping the loop<br>";
        break;
    }
    
    echo "Processing positive number: $num<br>";
}

echo "Loop completed.";
?>

Output:

Processing positive number: 7
Processing positive number: 3
Skipping negative number: -2
Processing positive number: 5
Found zero, stopping the loop
Loop completed.

This example shows how continue skips the current iteration and how break exits the loop entirely. It's like sorting mail – you skip the junk mail, process the regular mail, and stop when you find an urgent letter that needs immediate attention.

State Machines

While loops can implement simple state machines where each iteration represents a state transition:

<?php
// Simple vending machine state machine
$state = 'WAITING_FOR_COIN';
$credit = 0;
$productPrice = 125; // 1.25 in cents
$events = [
    'INSERT_COIN_25', 'INSERT_COIN_50', 'INSERT_COIN_100',
    'SELECT_PRODUCT', 'CANCEL'
];

// Simulate a sequence of events
$eventSequence = [
    'INSERT_COIN_25', 'INSERT_COIN_100', 'SELECT_PRODUCT'
];
$eventIndex = 0;

echo "Starting vending machine simulation<br>";

while ($state != 'IDLE' && $eventIndex < count($eventSequence)) {
    $event = $eventSequence[$eventIndex];
    $eventIndex++;
    
    echo "Current state: $state, Credit: $credit¢, Event: $event<br>";
    
    // State transitions
    switch ($state) {
        case 'WAITING_FOR_COIN':
            if ($event == 'INSERT_COIN_25') {
                $credit += 25;
                $state = 'COIN_INSERTED';
            } else if ($event == 'INSERT_COIN_50') {
                $credit += 50;
                $state = 'COIN_INSERTED';
            } else if ($event == 'INSERT_COIN_100') {
                $credit += 100;
                $state = 'COIN_INSERTED';
            }
            break;
            
        case 'COIN_INSERTED':
            if ($event == 'INSERT_COIN_25') {
                $credit += 25;
            } else if ($event == 'INSERT_COIN_50') {
                $credit += 50;
            } else if ($event == 'INSERT_COIN_100') {
                $credit += 100;
            } else if ($event == 'SELECT_PRODUCT') {
                if ($credit >= $productPrice) {
                    $change = $credit - $productPrice;
                    echo "Product dispensed! Change: $change¢<br>";
                    $credit = 0;
                    $state = 'IDLE';
                } else {
                    echo "Insufficient credit. Need " . ($productPrice - $credit) . "¢ more.<br>";
                }
            } else if ($event == 'CANCEL') {
                echo "Transaction cancelled. Returned: $credit¢<br>";
                $credit = 0;
                $state = 'WAITING_FOR_COIN';
            }
            break;
    }
}

echo "Final state: $state, Credit: $credit¢";
?>

Output:

Starting vending machine simulation
Current state: WAITING_FOR_COIN, Credit: 0¢, Event: INSERT_COIN_25
Current state: COIN_INSERTED, Credit: 25¢, Event: INSERT_COIN_100
Current state: COIN_INSERTED, Credit: 125¢, Event: SELECT_PRODUCT
Product dispensed! Change: 0¢
Final state: IDLE, Credit: 0¢

This state machine simulates a vending machine where each event triggers a state transition. It's like a board game where each turn changes the game state based on player actions and game rules.

Practice Exercises

Exercise 1: Number Guessing Game

Create a simple number guessing game where the computer "thinks" of a number, and the program simulates guesses until it finds the correct number:

<?php
// Start with this code template
$targetNumber = rand(1, 100);
$guess = 0;
$attempts = 0;

// Use a while loop to simulate guesses
// End solution should show the attempts and guesses made
?>

Hint:

Use a while loop that continues until the guess matches the target number. Generate random guesses and keep track of how many attempts were made.

Exercise 2: String Palindrome Checker

Create a function that checks if a string is a palindrome (reads the same backward as forward) using a while loop:

<?php
// Start with this code template
function isPalindrome($string) {
    // Remove spaces and convert to lowercase
    $string = strtolower(str_replace(' ', '', $string));
    
    // Use a while loop to check if the string is a palindrome
    // Return true if it's a palindrome, false otherwise
}

// Test cases
$testStrings = [
    "racecar",
    "A man a plan a canal Panama",
    "hello world",
    "Madam Im Adam"
];

foreach ($testStrings as $str) {
    echo "'$str' is " . (isPalindrome($str) ? "a palindrome" : "not a palindrome") . "<br>";
}
?>

Hint:

Use two pointers: one starting from the beginning of the string and one from the end. Use a while loop to move these pointers toward each other, comparing characters as you go.

Exercise 3: Prime Number Generator

Write a function that uses a while loop to generate all prime numbers up to a given limit:

<?php
// Start with this code template
function generatePrimes($limit) {
    $primes = [];
    
    // Use a while loop to generate prime numbers up to $limit
    // Return an array of prime numbers
}

$limit = 50;
$primes = generatePrimes($limit);
echo "Prime numbers up to $limit: " . implode(", ", $primes);
?>

Hint:

Use a while loop to iterate through numbers from 2 to the limit. For each number, check if it's divisible by any smaller number (except 1). If not, it's a prime number.

Homework Assignment

Create a program that uses different types of loops

Develop a PHP application that demonstrates the use of while loops in at least three different scenarios:

  1. Create a Fibonacci number generator that produces Fibonacci numbers up to a user-specified limit.
  2. Implement a simple text parser that processes a string until it finds a specific delimiter character.
  3. Develop a simulation of a dice game where a player rolls until they reach a certain score or bust.

Requirements:

  • Include meaningful comments explaining your code.
  • Implement at least one performance optimization technique discussed in class.
  • Format your output with appropriate HTML and CSS.
  • Each example should clearly demonstrate why a while loop is appropriate for that particular task.
  • Submit your code via the class GitHub repository by the next session.

Additional Resources

Coming Up Next

In our next session, we'll explore do-while loops and foreach loops, completing our journey through PHP's looping constructs. We'll also compare all the loop types and discuss when to use each one for optimal code clarity and performance.

Make sure to complete the homework assignment to reinforce your understanding of while loops before the next class!