1

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.

1

3 Answers 3

4

if doesn't even need a loop

if (isset($dbs[$_GET['id']])) {
    echo sprintf('On ID %s is %s', $_GET['id'], $dbs[$_GET['id']]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() in any code for any reason -- it should be printf() without echo every time.
3

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.

Comments

1

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
}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.