0

I have a long list of PHP switch statements that differ only in a substring, such as with strx, stry and strz as shown below:

    switch ($block_name) {
            case "strx_blk":
                    $list = &$GLOBALS['strx_list'];
                    $checked = $GLOBALS['strx_checked'];
                    break;
            case "stry_blk":
                    $list = &$GLOBALS['stry_list'];
                    $checked = $GLOBALS['stry_checked'];
                    break;
            case "strz_blk":
                    $list = &$GLOBALS['strz_list'];
                    $checked = $GLOBALS['strz_checked'];
                    break;
    }

I would like to know if there a more compact way to express the same logic in PHP. There could be a large number of such repetitions hence the necessity for automation.

2 Answers 2

1

You can split up $block_name and concatenate the prefix to the array indexes.

$array = explode('_', $block_name);
$prefix = $array[0];
$list = &$GLOBALS[$prefix . "_list"];
$checked = $GLOBALS[$PREFIX . "_checked"];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I got the gist. list($prefix) = explode("_", $block_name); can replace the first two lines I think.
Yes, you can do that if you like.
0
$part1 = 'strz';
$part2 = 'list';
var_dump($GLOBALS[$part1 . '_' . $part2]);

1 Comment

But $part1 changes depending on the value of $block_name.

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.