I’m looking for the way to combine 2 foraech loops into one (merge 2 functions): The result function should return both: ($is – boolean & $d – array). Traversable data in both functions – the same. Is it possible? What will be a good solution for that?
public function func1($p, $c) { $is = 0; if (!empty($p)) { foreach($p as $k=>$v) { if ((!empty($c['prod']) && $c['prod'] == $v['ref'] && $c['status'])) { $is = 1; break; } } } return $is; } public function func2($p) { $d = []; if (!empty($p)) { foreach($p as $k=>$v) { $prod = [ 'name' => $v['name'], 'price' => $v['price'], 'reference' => $v['ref'] ]; $d[] = $prod; } } return $d; }
Thanks.
Advertisement
Answer
My take, but not tested.
public function func3($p, $c) { $is = 0; $d = []; if (!empty($p)) { foreach($p as $k=>$v) { $d[] = [ 'name' => $v['name'], 'price' => $v['price'], 'reference' => $v['ref'] ]; if ($is === 0 && (!empty($c['prod']) && $c['prod'] == $v['ref'] && $c['status'])) { $is = 1; } } } return [$is, $d]; }