How can we accomplish this foreach task with a built-in PHP array function?
$requestProducts = $this->request['products'];
$products = [];
foreach ($requestProducts as $product) {
if (!empty($product['search']['value'])) {
array_push($products, [
'name' => $product['name'],
'title' => $product['title'],
'search' => $product['search']['value']
]);
}
}
Something in this way I would like to have but without null values.
$requestProducts = $this->request['products'];
$products = array_map(function ($product) {
if (!empty($product['search']['value'])) {
return [
'name' => $product['name'],
'title' => $product['title'],
'search' => $product['search']['value']
];
}
return null; // without null
}, $requestProducts);
$products = array_filter($products) // without this
The task should look encapsulated.
foreachapproach is good enough for your case