1.2.1318. Use Array Functions¶
There are a lot of native PHP functions for arrays. It is often faster to take advantage of them than write a loop.
array_push() : use array_merge()
array_slice() : use array_chunk()
index access : use array_column()
append []: use array_merge()
addition : use array_sum()
multiplication : use array_product()
concatenation : use implode()
ifthen : use array_filter()
extract one index $s[‘index’] : use array_column()
apply a method to each element : use array_map() or array_walk()
<?php
$all = implode('-', $s).'-';
// same as above
$all = '';
foreach($array as $s) {
$all .= $s . '-';
}
// extract one index in an array
$extract = [];
foreach($array as $a) {
$extract[] = $a['index'];
}
$extract = array_column($array, 'index');
?>
See also Array Functions and No array_merge() In Loops.
1.2.1318.1. Connex PHP features¶
1.2.1318.1.1. Suggestions¶
Remove the loop and use a native PHP function
Add more expressions to the loop : batching multiple operations in one loop makes it more interesting than running separates loops.
1.2.1318.1.2. Specs¶
Short name |
Structures/UseArrayFunctions |
Rulesets |
|
Exakat since |
1.8.8 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |