mrpatg
mrpatg

Reputation: 10117

Executing two functions as part of a foreach statement

This is more of a best practices question:

Say I want to execute two functions in a foreach statement (to combine the returns of these functions for use as a single element for the loop), would I combine them in the statement such as:

foreach(function1($data).function2($data) AS $key=>$value)

or is there a better way to do this?

Upvotes: 1

Views: 188

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

First, arrays are concatenated with + or array_merge(), the dot is only used for strings, so you would get the string "ArrayArray".

Second, for better readability and maintainability you should separate the function calls and the loop initialization:

$fileList = function1($data); 
$fileList += function2($data);
foreach($fileLists AS $key=>$value) {
}

Note that this does not make a difference in outcome or performance of the code, it just helps debugging and understanding (which is generally more important by the way).

Upvotes: 1

Narek
Narek

Reputation: 3823

If function1 and function2 return arrays then:

foreach(array_merge(function1($data),function2($data)) AS $key=>$value)

Upvotes: 2

Related Questions