kalessil / phpinspectionsea

A Static Code Analyzer for PHP (a PhpStorm/Idea Plugin)
https://plugins.jetbrains.com/plugin/7622?pr=phpStorm
Other
1.44k stars 118 forks source link

Slow array function used in loop: Looping over something else then the array? #1713

Open davidmosterd opened 3 years ago

davidmosterd commented 3 years ago

Description: Say you are looping over something else than an array, WooCommerce orders in my case. I create an array with defaults, but on a certain condition, I want to add to these defaults another array. The inspection says it's slow to use an array in a loop, and if I were looping over this array I would understand this. But for associative arrays with strings there is no spread operator and typing out all these options is gross syntax.

It should maybe check array_merge is used in a loop that has nothing to do with the array itself? I see no other way of doing it with elegant syntax. Or am I missing something?

Example:

<?php

foreach( $orders as $order ) {
    $meta = [
        'thing_1' => 2,
        'thing_2' => 4
    ];

    if ( $someCondition ) {
        $meta = array_merge( $meta, [
            'thing_1' => 3,
            'thing_5' => 4,
            'thing_8' => 9,
            'thing_13' => 5,
        ] );
    }
}
ea-inspections-team commented 2 years ago

Thanks for reporting @davidmosterd ! Actually, that a valid concern - the inspection should not report this as the variable was assigned in the first statement of the loop. We'll fix this.

davidmosterd commented 2 years ago

Thanks! I disabled the inspection, but I'd rather keep it on ofc.