PHP array copy certain keys, built-in functions? Nested loop performance?

后端 未结 2 1367
孤独总比滥情好
孤独总比滥情好 2021-02-07 12:09

I have a PHP array that I\'d like to duplicate but only copy elements from the array whose keys appear in another array.

Here are my arrays:

$data[123] =         


        
2条回答
  •  感情败类
    2021-02-07 12:44

    I worked it out - I almost had it above.I thought I'd post the answer anyway for completeness. Hope this helps someone out!

    array_intersect_key($data, array_flip($keys_to_copy))

    Use array_flip() to switch $keys_to_copy so it can be used within array_intersect_keys()

    I'll run some tests to compare performance between the manual loop above, to this answer. I would expect the built-in functions to be faster but they might be pretty equal. I know arrays are heavily optimised so I'm sure it will be close.

    EDIT:
    I have run some benchmarks using PHP CLI to compare the foreach() code in my question with the code in my answer above. The results are quite astounding.
    Here's the code I used to benchmark, which I think is valid:

     $value) {
        if ( in_array($key, $keys_to_copy)) {
            $copied_data[$key] = $value;
        }
    }
    echo 'foreach: '.(microtime(TRUE) - $timer_start)."s\r\n";
    
    // BUILT-IN ARRAY FUNCTIONS
    $timer_start = microtime(TRUE);
    $copied_data = array_intersect_key($data, array_flip($keys_to_copy));
    echo 'built-in: '.(microtime(TRUE) - $timer_start)."s\r\n";
    ?>

    And the results...
    foreach: 662.217s
    array_intersect_key: 0.099s

    So it's much faster over loads of array elements to use the PHP array functions rather than foreach. I thought it would be faster but not by that much!

提交回复
热议问题