I'm creating a comma delimited string for an SQL query. I would like to know what is better arraymap or a foreach loop. Here are my two examples:
$group_ids = "";
foreach ($group_array as $group_id) {
$group_ids .= $group_id . ",";
}
$group_ids = rtrim($group_ids, ',');
vs
$group_ids = "";
array_map(function ($group_id) use ($group_ids) {
$group_ids .= $group_id . ",";
return;
}, $group_array);
$group_ids = rtrim($group_ids, ',');
Or is there a better way? Or is there literally not much difference?
Array_map()is slower thanforeach()rtrim(str_repeat('?,', count($group_array)), ',')) and then executing the query with $group_array as an array of arguments for binding is even betterarray_map()should not be called if you are not going to use its return value. If you want a functional iterator, but do not intend to use the return value, usearray_walk().