I'm trying to route set of array, but it's not working.
<?php
$routes = array('home'=>'Home Page','about'=>'About Me');
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch($action) {
foreach($routes as $key => $value) {
case $key:
echo $value;
break;
}
}
But instead, it returns Parse error: syntax error, unexpected token "foreach", expecting "case" or "default" or "}"
CodePudding user response:
I don't think you can do that, even if you could, I would advise against it as it is not a conventional practice.
Why not just use something like the following?
<?php
$routes = array('home'=>'Home Page','about'=>'About Me');
$action = isset($_GET['action']) ? $_GET['action'] : '';
if (array_key_exists($action, $routes)) {
echo $routes[$action];
} else {
// Do you error handling here.
}
CodePudding user response:
Try to solve it this way, with using filter_input on get variable:
<?php
$routes = array('home'=>'Home Page','about'=>'About Me');
$action = filter_input(INPUT_GET, 'action');
if ($action) {
echo $routes[$action];
}