Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading