1

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.

1
  • foreach approach is good enough for your case Commented Jan 6, 2018 at 12:34

1 Answer 1

1

Solution with array_reduce:

$requestProducts = $this->request['products'];

$products = array_reduce(
    // your values
    $requestProducts,                   
    // reducing function
    function ($t, $product) {
        if (!empty($product['search']['value'])) {
            $t[] = [
                'name' => $product['name'],
                'title' => $product['title'],
                'search' => $product['search']['value']
            ];
        }

        return $t;
    }, 
    // initial value for reduced items
    []
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.