How can dynamic routing be implemented in PHP to avoid unnecessary redirection loops?

To implement dynamic routing in PHP without causing unnecessary redirection loops, you can maintain a list of valid routes and check if the requested route exists before redirecting. This can be achieved by using an associative array where keys represent valid routes and values are the corresponding file paths or functions to handle the requests.

<?php

// Define a list of valid routes
$routes = [
    'home' => 'home.php',
    'about' => 'about.php',
    'contact' => 'contact.php'
];

// Get the requested route
$route = isset($_GET['route']) ? $_GET['route'] : 'home';

// Check if the requested route exists
if (array_key_exists($route, $routes)) {
    include $routes[$route];
} else {
    // Handle invalid routes here
    echo '404 - Page not found';
}

?>