使用数组中的值作为switch-case键

I’m working on an app, and I’m stuck.

I want to do foreach inside switch like this:

<?PHP
$gtid = $_GET['id'];
// ID(key) => value
$dbs  = array(
    "ZTI10" => "Example1",
    "O1JTQ" => "Example2",
    "4V1OR" => "Example3"
);

switch($gtid){

foreach ($dbs as $key => $value) {

    case $key:
        echo "On ID $key is $value";
        break;

  }
}
?>

Is that even possible? Or is there any other way to do what I want here?

Thanks in advance.

if doesn't even need a loop

if (isset($dbs[$_GET['id']])) {
    echo sprintf('On ID %s is %s', $_GET['id'], $dbs[$_GET['id']]);
}

No, you can't do that. Use a simple if statement inside your foreach loop instead:

foreach ($dbs as $key => $value) {
    if ($gtid == $key) {
        echo "On ID $key is $value";
        break;
  }
}

The break here causes the execution to immediately jump out of the foreach loop, so it won't evaluate any other elements of the array.

No.

Easy way to do this:

<?php

$gtid = $_GET['id'];

$dbs  = array(
    "ZTI10" => "Example1",
    "O1JTQ" => "Example2",
    "4V1OR" => "Example3"
);

if ( isset($dbs[$gtid]) ) {
    echo "On ID $gtid is $dbs[$gtid]";
} else {
    // default
}

?>