PHP: Fastest way to handle undefined array key

后端 未结 8 1642
梦如初夏
梦如初夏 2020-12-08 07:13

in a very tight loop I need to access tenthousands of values in an array containing millions of elements. The key can be undefinied: In that case it shall be legal to return

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 07:37

    Just a sudden idea that would have to be tested, but did you try using array_intersect_key() to get the existing values and a array_merge to fill() the rest ? It would remove the need of a loop to access the data. Something like that :

    $searched_keys = array ('key1' => null, 'key2' => null); // the list of the keys to find
    
    $exiting_values = array_intersect_key($lookup_table, $searched_keys);
    $all_values = array_merge($searched_keys, $exiting_keys);
    

    Please note that I did not tried it performance-wise.

提交回复
热议问题