In PHP, can I get the total number of case statements in a switch statement?

Is there a way to return the total number of instances (case) in a switch statement? Something like that:

$id = $_GET['id'];

switch ($id) {
  case "item1" :
  $data = 'something1';
  break;

  case "item2" :
  $data = 'something2';
  break;
}

echo $data;

But the argument is that they have several files with these switch statements, but their number depends on the file. Ideally, I would like to be able to scroll through these switch statements, incrementing the "id". Any ideas on whether this is possible?

+3
source share
7 answers

If you just assign values ​​based on a different value, you can instead of array :

$idToData = array(
    'item1' => 'something1',
    'item2' => 'something2',
);
$data = 'default';
if (isset($_GET['id']) && array_key_exists($_GET['id'], $idToData)) {
    $data = $idToData[$_GET['id']];
}
echo $data;

, extended, count()

+7

$id break... . , , ?

grep ,

find -name '*php' | xargs grep 'case'
+1

- , , . , , : case, , . .

for($id = 1; !$quit; $id++)
{
    switch("item" . $id) {
    case "item1":
         // Do something
         break;
    case "item<n>":
         // Do something else
         break;
    default:
         $quit = true;
    }
}

: case ... ?

+1

, , , token_get_all(), , , .

+1

, token_get_all(). () PHP. ( ), switch, case. , switch.

+1

, , URL :

somesite.com/ajax/getinfo.php?id=news

$_GET [id] .

:

$section=$_GET[id];
switch($section) {
case "1":
break;
.
.
.
default:

}

, . , , .

0
source

Actually, this code will work:

$i = 0;
switch(something)
{
    case "item".$i++: //something
        break;
    case "item".$i++: //something
        break;
    default: //something
        break;
}
0
source

Source: https://habr.com/ru/post/1707213/


All Articles