简体   繁体   中英

pros and cons of array extracting methods

Which method is good to get values from array using in loops.

 1. list()
 2. extract()
 3. Normal extracting like $array['id']

code snippet:

$sel = mysql_query("SELECT id,name from user");
while($get = mysql_fetch_array($sel)){
 //Which one is good
 extract($get);  
 loop($id,$name)=$get;
 $id = $get['id'];
} 

I like to know pros and cons of these methods. or any other method exists.

Thanks

extract() should be used with most care. But it is perfectly fine if you want to get a limited set of known variables from an associative array.

list() however is usually unsuited for associative arrays. It's for numerically indexed arrays, and assigns them to local variables. list() is sort of equivalent to extract(array_combine($list_keys, $array_values));

Finally the normal array access, most common and most advisable if you only need to access a few array entries. Very obviously also preferred most everywhere because it leads to the least conflicts with existing local variables.

Avoid extract() wherever possible (which is most places). It does things to the symbol table that sane languages do not allow.

Between list() and explicit array extraction, list() is probably preferable, as it's a bit more concise. It requires that you have an ordered array, though, rather than an associative array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM