Home > Article > Backend Development > Which foreach method is better for processing list data in PHP?
In development, it is often necessary to process list data taken from the database,
There are three writing methods I have seen below, all of which can get the same result. I am always accustomed to using the first one.
Which one is better in terms of readability and performance?
List data such as:
<code>$list = [ [ 'uid'=>100, 'username'=>'test100', 'nickname'=>'php_1', 'gender'=>1, ], [ 'uid'=>200, 'username'=>'test200', 'nickname'=>'php_2', 'gender'=>2, ], [ 'uid'=>300, 'username'=>'test300', 'nickname'=>'php_3', 'gender'=>0, ], ];</code>
<code>foreach($list as $k=>$v){ if($v['gender']==0){ $list[$k]['gender']='妖人'; }else{ $list[$k]['gender']='人'; } }</code>
<code>foreach($list as &$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; } }</code>
<code> $data = []; foreach($list as $k=>$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; } $data[] = $v; }</code>
In development, it is often necessary to process list data taken from the database,
There are three writing methods I have seen below, all of which can get the same result. I am always accustomed to using the first one.
Which one is better in terms of readability and performance?
List data such as:
<code>$list = [ [ 'uid'=>100, 'username'=>'test100', 'nickname'=>'php_1', 'gender'=>1, ], [ 'uid'=>200, 'username'=>'test200', 'nickname'=>'php_2', 'gender'=>2, ], [ 'uid'=>300, 'username'=>'test300', 'nickname'=>'php_3', 'gender'=>0, ], ];</code>
<code>foreach($list as $k=>$v){ if($v['gender']==0){ $list[$k]['gender']='妖人'; }else{ $list[$k]['gender']='人'; } }</code>
<code>foreach($list as &$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; } }</code>
<code> $data = []; foreach($list as $k=>$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; } $data[] = $v; }</code>
Use 1 more often
Although 2 is the simplest way to write, there are pitfalls in quoting under foreach
If you use the $v variable again outside of foreach, the last value of foreach may be changed. , of course it can be guaranteed that this problem will not occur if it is not used
array_map
I generally use the first way of writing
The second way of writing is prone to problems
The recommended way to quote is writing method 2
The second method is better. You have already foreached it. There is already a one-dimensional array, so why do you need to fetch it from the list?
select if(gender=0,'魔人','人') as gendername ……
Get used to the first method