Reputation: 663
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.
Upvotes: 1
Views: 116
Reputation: 113
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
}
?>
Upvotes: 1
Reputation: 11447
if doesn't even need a loop
if (isset($dbs[$_GET['id']])) {
echo sprintf('On ID %s is %s', $_GET['id'], $dbs[$_GET['id']]);
}
Upvotes: 4
Reputation: 149020
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.
Upvotes: 3