andybeak icon

Loops and logic branches

andybeak | PRO | 02/26/25 01:51:44 PM UTC | 0 ⭐ | 10021 👁️ | Never ⏰ | []
PHP |

8.21 KB

|

None

|

0 👍

/

0 👎

<?php
/*
 * PHP LOOPS AND LOGIC BRANCHES
 * This file demonstrates all the different types of loops and logic branches in PHP
 */
 
echo "==========================================\n";
echo "IF/ELSE STATEMENTS\n";
echo "==========================================\n";
 
// Basic if statement
$condition = true;
if ($condition) {
    echo "This will be executed because the condition is true\n";
}
 
// If/else statement
$temperature = 25;
if ($temperature > 30) {
    echo "It's hot outside\n";
} else {
    echo "It's not that hot\n";
}
 
// If/elseif/else statement
$score = 85;
if ($score >= 90) {
    echo "Grade: A\n";
} elseif ($score >= 80) {
    echo "Grade: B\n";
} elseif ($score >= 70) {
    echo "Grade: C\n";
} elseif ($score >= 60) {
    echo "Grade: D\n";
} else {
    echo "Grade: F\n";
}
 
// Ternary operator (short if/else)
$age = 20;
$canVote = ($age >= 18) ? "Yes" : "No";
echo "Can vote: $canVote\n";
 
// Null coalescing operator (PHP 7+)
$username = null;
$displayName = $username ?? "Guest";
echo "Hello, $displayName\n";
 
// Nested if statements
$isLoggedIn = true;
$isAdmin = true;
if ($isLoggedIn) {
    echo "User is logged in\n";
    if ($isAdmin) {
        echo "User has admin privileges\n";
    } else {
        echo "User has regular privileges\n";
    }
} else {
    echo "User is not logged in\n";
}
 
echo "\n==========================================\n";
echo "SWITCH STATEMENTS\n";
echo "==========================================\n";
 
// Switch statement
$dayOfWeek = 3;
switch ($dayOfWeek) {
    case 1:
        echo "Monday\n";
        break;
    case 2:
        echo "Tuesday\n";
        break;
    case 3:
        echo "Wednesday\n";
        break;
    case 4:
        echo "Thursday\n";
        break;
    case 5:
        echo "Friday\n";
        break;
    case 6:
    case 7:
        echo "Weekend\n";
        break;
    default:
        echo "Invalid day\n";
        break;
}
 
// Switch with fall-through (no break)
$month = "Feb";
switch ($month) {
    case "Jan":
        echo "31 days\n";
        break;
    case "Feb":
        echo "28 or 29 days\n";
        break;
    case "Mar":
        echo "31 days\n";
        break;
    case "Apr":
        echo "30 days\n";
        break;
    // ... more cases
}
 
echo "\n==========================================\n";
echo "MATCH EXPRESSION (PHP 8+)\n";
echo "==========================================\n";
 
// Match expression (PHP 8+)
// Will only work if you're running PHP 8 or higher
$statusCode = 404;
/* 
$message = match($statusCode) {
    200, 201 => "Success",
    400 => "Bad request",
    401 => "Unauthorized",
    403 => "Forbidden",
    404 => "Not found",
    default => "Unknown status code"
};
echo "HTTP Status: $message\n";
*/
// For PHP 7 and below, use switch statement instead
$message = "";
switch($statusCode) {
    case 200:
    case 201:
        $message = "Success";
        break;
    case 400:
        $message = "Bad request";
        break;
    case 404:
        $message = "Not found";
        break;
    default:
        $message = "Unknown status code";
}
echo "HTTP Status: $message\n";
 
echo "\n==========================================\n";
echo "FOR LOOPS\n";
echo "==========================================\n";
 
// Basic for loop
echo "Basic for loop:\n";
for ($i = 0; $i < 5; $i++) {
    echo "Iteration $i\n";
}
 
// For loop with multiple expressions
echo "\nFor loop with multiple expressions:\n";
for ($i = 0, $j = 10; $i < 5; $i++, $j--) {
    echo "i = $i, j = $j\n";
}
 
// For loop with break
echo "\nFor loop with break:\n";
for ($i = 0; $i < 10; $i++) {
    if ($i == 5) {
        break; // Exit the loop when $i is 5
    }
    echo "Iteration $i\n";
}
 
// For loop with continue
echo "\nFor loop with continue:\n";
for ($i = 0; $i < 10; $i++) {
    if ($i % 2 == 0) {
        continue; // Skip even numbers
    }
    echo "Odd number: $i\n";
}
 
echo "\n==========================================\n";
echo "FOREACH LOOPS\n";
echo "==========================================\n";
 
// Foreach loop with array
$fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
echo "Fruits list:\n";
foreach ($fruits as $fruit) {
    echo "- $fruit\n";
}
 
// Foreach with key => value
$person = [
    "name" => "John Doe",
    "age" => 30,
    "email" => "[email protected]",
    "location" => "New York"
];
echo "\nPerson details:\n";
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
 
// Foreach with reference (&) to modify values
echo "\nModifying array values with foreach:\n";
$numbers = [1, 2, 3, 4, 5];
echo "Before: " . implode(", ", $numbers) . "\n";
foreach ($numbers as &$number) {
    $number *= 2; // Double each number
}
unset($number); // Unset the reference
echo "After: " . implode(", ", $numbers) . "\n";
 
echo "\n==========================================\n";
echo "WHILE LOOPS\n";
echo "==========================================\n";
 
// Basic while loop
echo "Basic while loop:\n";
$count = 0;
while ($count < 5) {
    echo "Count: $count\n";
    $count++;
}
 
// While loop with break
echo "\nWhile loop with break:\n";
$count = 0;
while (true) { // Infinite loop
    echo "Count: $count\n";
    $count++;
    if ($count >= 5) {
        break; // Exit the loop
    }
}
 
// While loop with continue
echo "\nWhile loop with continue:\n";
$count = 0;
while ($count < 10) {
    $count++;
    if ($count % 2 == 0) {
        continue; // Skip even numbers
    }
    echo "Odd count: $count\n";
}
 
echo "\n==========================================\n";
echo "DO-WHILE LOOPS\n";
echo "==========================================\n";
 
// Basic do-while loop
echo "Basic do-while loop:\n";
$count = 0;
do {
    echo "Count: $count\n";
    $count++;
} while ($count < 5);
 
// Do-while that executes at least once
echo "\nDo-while with condition that would fail immediately in a while loop:\n";
$count = 10;
do {
    echo "This will execute once even though count is already 10\n";
    $count++;
} while ($count < 5);
 
echo "\n==========================================\n";
echo "NESTED LOOPS\n";
echo "==========================================\n";
 
// Nested for loops (creating a simple multiplication table)
echo "Multiplication table (3x3):\n";
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        $product = $i * $j;
        echo "$i × $j = $product\n";
    }
    echo "-----\n";
}
 
// Nested loop with break/continue
echo "\nNested loops with break and continue:\n";
for ($i = 0; $i < 3; $i++) {
    echo "Outer loop $i:\n";
    for ($j = 0; $j < 5; $j++) {
        if ($j == 1) {
            continue; // Skip when $j is 1
        }
        if ($j == 4) {
            break; // Exit inner loop when $j is 4
        }
        echo "  Inner loop $j\n";
    }
}
 
// Breaking out of nested loops with labels (PHP 8+)
echo "\nLabels can be used to break out of nested loops (PHP GOTO):\n";
 
for ($i = 0; $i < 3; $i++) {
    echo "Outer loop $i:\n";
    for ($j = 0; $j < 3; $j++) {
        echo "  Inner loop $j\n";
        if ($i == 1 && $j == 1) {
            echo "  Breaking out of all loops\n";
            goto end_of_loops; // Break out of both loops
        }
    }
}
end_of_loops:
echo "Loops have ended\n";
 
echo "\n==========================================\n";
echo "ALTERNATIVE SYNTAX (used in templates)\n";
echo "==========================================\n";
 
// Alternative syntax for if statements
$showSection = true;
if ($showSection): ?>
    This is HTML that would be shown if $showSection is true.
<?php else: ?>
    This is HTML that would be shown if $showSection is false.
<?php endif;
 
// Alternative syntax for loops
$colors = ["Red", "Green", "Blue"];
?>
 
<ul>
<?php foreach ($colors as $color): ?>
    <li><?php echo $color; ?></li>
<?php endforeach; ?>
</ul>
 
<?php
// Alternative switch syntax
$userRole = "admin";
switch ($userRole):
    case "admin":
        echo "Welcome, Administrator!";
        break;
    case "editor":
        echo "Welcome, Editor!";
        break;
    default:
        echo "Welcome, User!";
        break;
endswitch;
?>

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎