Szandor
Szandor

Reputation: 403

Difference between foreach( if() ) and if( foreach() )

I have a piece of code that looks like this at the moment:

foreach ($array['subarray'] as $current) {

    if ($some_variable === 'some_string') {

        $new_array[] = $current['some_name'];

    } else {

        $new_array[] = $current['another_name'];

    }
}

The same code could also be written like this:

if ($some_variable === 'some_string') {

    foreach ($array['subarray'] as $current) {

        $new_array[] = $current['some_name'];

    }

} else {

    foreach ($array['subarray'] as $current) {

        $new_array[] = $current['another_name'];

    }
}

My question is; is there a real difference between the two or is it just down to preference? I'm mostly talking performance here, but also if there is some standard to how nesting is usually done in PHP.

Upvotes: 1

Views: 216

Answers (1)

Furgas
Furgas

Reputation: 2844

Considering those particular examples, the second example is better in performance (if condition used only once), but this approach would be even better:

$new_key = 'default_value';
if ($some_variable === 'some_string') {
    $new_key = 'special_value';
}

foreach ($array['subarray'] as $current) {
    $new_array[] = $current[$new_key];
}

EDIT

If the difference is not only the key name, then I would base the choice on complexity and similarity of code in foreach, taking DRY principle and code readibility into account first and micro optimization (usually not worth it) last. So, it depends heavily on what you are doing in those loops, how critical is your system and how big are your data structures.

Upvotes: 5

Related Questions