Ad

Foreach Inside Foreach (Php - Laravel) Inside If Give Double Outputs

- 1 answer

I want to disable the input checkboxes.

$value1->name has the values(product1, product2, product3, product4, product5)
$value2->name has the values(product3, product4)
@foreach ($products_table1 as $value1)
    @foreach($products_table2 as $value2)
        @if($value1->name != $value2->name)
            disabled
        @endif
    @endforeach
@endforeach

I want to output as a result this:

<input type="checkbox" disabled> Product 1
<input type="checkbox" disabled> Product 2
<input type="checkbox" > Product 3
<input type="checkbox" > Product 4
<input type="checkbox" disabled> Product 5

But instead of this I get:

<input type="checkbox" disabled disabled > Product 1
<input type="checkbox" disabled disabled > Product 2
<input type="checkbox" disabled > Product 3
<input type="checkbox" disabled > Product 4
<input type="checkbox" disabled disabled > Product 5

What Can I do to prevent the double output? Is there alternatives options? I am trying to create a product filter with checkboxes.

Ad

Answer

You could create an array-diff first; creating a list of the products in value1 that are not in value2 and then looping this new array only:

http://php.net/manual/en/function.array-diff.php

The other option which avoids explicitly allocating this difference array is to use the boolean operator 'in-array':

http://php.net/manual/en/function.in-array.php

Either of these should be more efficient than the original, since as you're noticing, you're actually comparing each set of two items twice in the nested foreach

Ad
source: stackoverflow.com
Ad