Networkbell
Networkbell

Reputation: 15

Optimize an array function

Here is an example of test code. I wonder how to optimize this code, knowing that in my development code, the original array comes from an API that I retrieve, then that I transform according to my needs and calculations in a class with functions methods (there is a lot of transformation in $rep with ternary operators). The example here is for simplicity:

When you call the function testArray() several hundred times, the calculation time begins to become long, too long. I wonder if there's a way to optimize this and code more elegantly.

 $data = array(
        "lemon" => 'test1',
        "tomato" => 'test2',
        "cofee" => 'test3',
        "tree" => 'test4'
    );
    
    
    function testArray($data)
    {
    
        $rep = array(
            'yellow' => $data['lemon'],
            'red' => $data['tomato'],
            'brown' => $data['cofee'],
            'green' => $data['tree']
        );
        return $rep;
    }
    
    echo testArray($data)['yellow'];    // test1
    echo testArray($data)['red'];       // test2
    echo testArray($data)['brown'];     // test3
    echo testArray($data)['green'];     // test4

thank you, I'm stuck a bit to find a more efficient way.

Upvotes: 0

Views: 99

Answers (1)

ikhvjs
ikhvjs

Reputation: 5977

You don't need to call the function multiple time. Just store it to a variable and use it later.

$data = array(
        "lemon" => 'test1',
        "tomato" => 'test2',
        "cofee" => 'test3',
        "tree" => 'test4'
    );
    
    
    function testArray($data)
    {
    
        $rep = array(
            'yellow' => $data['lemon'],
            'red' => $data['tomato'],
            'brown' => $data['cofee'],
            'green' => $data['tree']
        );
        return $rep;
    }
    
    $transformedData = testArray($data);
    echo transformedData['yellow'];    // test1
    echo transformedData['red'];       // test2
    echo transformedData['brown'];     // test3
    echo transformedData['green'];     // test4

Upvotes: 2

Related Questions