1
\$\begingroup\$

I am asking your preference between two similar solutions.

First way :

public function test($myvar) {

    switch ($myvar) {   
        case 'test1': return [
                          'value' => 'Value of test1',
                          'short' => 'Val 1'
                      ];
        break;
     }
}

$this->test('test1')['short']  // Val 1

Second way:

public function test($myvar, $key) {

    switch ($myvar) {   
        case 'test1': $array = [
                          'value' => 'Value of test1',
                          'short' => 'Val 1'
                      ];
    }

    return $array[$key];
}

$this->test('test1', 'short')  // Val 1

Even if both function return same value, what is the most elegant and readable way for you guys ?

\$\endgroup\$
1
  • \$\begingroup\$ From usage POV: will you ever use full array outside test()? If not then you have absolutely no reason to return full array and 2nd solution is preferable. From performance POV: In 2nd solution do you need to build full array each time? You already know which value you want to return... \$\endgroup\$ Commented Oct 19, 2015 at 11:38

1 Answer 1

1
\$\begingroup\$

This question is not simply preference, the second method is better than the first for the following reasons:

In the first, you initialise a function test and it returns an array: test[] So, alongside the string to test against 'short' in the memory, you now have those three things in the memory.

Whereas, in the second example, you don't return an array, and the 'short' string is only used as a parameter, by doing this you now can only have two things in the memory.

Therefore, the second code block is better than the first.

Also, in the spirit of Code Review, you can further improve the second code block, by not actually assigning $array, or using a switch.

public function test($myVar, $key) {
    return [
        'test1' => [
            'value' => 'Value of test1',
            'short' => 'Val 1'
        ]
    ][$myVar][$key];
}

$this->test('test1', 'short')  // Val 1
  • $myvar should also be in camelCase: $myVar
\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.