J
J
jacksparrow2015-10-16 23:21:19
PHP
jacksparrow, 2015-10-16 23:21:19

Which code option is better?

The question of an ideological nature arose as to how to write correctly. So:

function a($data){
$result=[];
foreach($data as $item){
if($item==1){
$result[]=$item;
}
}
return $result;
}

Or an alternative:
function a($data){
$result=[];
foreach($data as $item){
if($item!=1){
continue;
}
$result[]=$item;
}
return $result;
}

Added: The question is not of this example, but the ratio of execution by condition to interruption by non-compliance with the condition.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cat Anton, 2015-10-16
@27cm

php.net/manual/en/function.array-filter.php

$data = array_filter($data, function ($item) {
    return ($item == 1);
});

I
IceJOKER, 2015-10-16
@IceJOKER

The first option, of course, is shorter and more readable (just for this case, but otherwise it depends on the code)

S
Sergey, 2015-10-17
Protko @Fesor

Escobar's axiom, array_filter is always better in terms of code readability.
But in general, the first option wins because it is tritely readable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question