OM The Eternity
OM The Eternity

Reputation: 16214

While using a switch case loop, can i use the for loop for iterating the cases?

In PHP, While using a switch case loop, can i use the for loop for iterating the cases? for example

switch .....

foreach($xyz as $abc)

{
 CASE:$abc
}

default;

UPDATE

I am fetching the value from DB, this value is name of table, by using "case" I want to execute a particular query according to the table name..

Is this possible?

Upvotes: 1

Views: 5433

Answers (3)

EDIT: as per the OP's comments , i am writing this answer

   $query=null;
    switch($tableName):
    {
    case "table1":
    $query="...";
    break;
    case "table2":
    $query="...";
    break;
    case "table3":
    $query="...";
    break;
    }
    ....

here goes  logic to  execute that query

If you have too many tables then put those querys in array check like this ,

$arr = array("table1"=>"query1","table2"=>"query2","table3"=>"query3",....);
$query  = $arr[$tableName];

here goes the logic to execute query

Upvotes: 1

Finbarr
Finbarr

Reputation: 32126

I do not think that you can dynamically generate CASE declarations in PHP switch statements in this way.

What you are talking about doing is getting all of your tables in an array, then looping through them inside a switch statement to automatically declare your CASE statements. You cannot do this.

It generates:

Parse error: syntax error, unexpected T_FOREACH, expecting T_CASE or T_DEFAULT

Upvotes: 2

pinkgothic
pinkgothic

Reputation: 6179

You probably just want to put the switch statement into the foreach?

foreach ($tables as $table) {
    switch ($table) {
        case 'table_one' :
            // do something here
            break;
        case 'table_two' :
            // do something here
            break;
        case 'table_three' :
            // do something here
            break;
        default :
            // do some error handling here
            break;
    }
}

Alternatively, a switch isn't that easy to read, consider going away from a switch and using an array-powered if, especially if you could dynamically create what you want to do each case:

$tables = array('table_one', 'table_two', 'table_three');
if (in_array($table, $tables)) {
    // do something here
} else {
    // do some error handling here
}

That's a lot more readable, even if your array has a lot of elements.

Upvotes: 1

Related Questions