php in_array between 2 arrays

Issue

I am trying to determine which elements coincide in 2 arrays. The issue is that only the last element in my second array is selected instead of all 3. What am I missing here?

<?php
    
$containers = [
    0 => ['id'=>'1', 'name'=>'Peta'],
    1 => ['id'=>'2', 'name'=>'Epta'],
    3 => ['id'=>'3', 'name'=>'Fras'],
    4 => ['id'=>'4', 'name'=>'Maxs'],
    5 => ['id'=>'5', 'name'=>'Gtay'],
    6 => ['id'=>'6', 'name'=>'Prat'],
    7 => ['id'=>'7', 'name'=>'Drat'],
];

$invoices = [
    0 => ['id'=>'1', 'name'=>'Lebo'],
    1 => ['id'=>'3', 'name'=>'Efta'],
    2 => ['id'=>'4', 'name'=>'Gadr'],
];

foreach ($containers as $container) {
    
    foreach ($invoices as $invoice) {
    
        if (in_array($container['id'], $invoice)) {
            $selected = 'selected';
        } else {
            $selected = '';
        }
    
    }
    
    echo $container['name'].' -> '.$selected.'<br>';
    
} ?>

Solution

Add "break" after found in array.

<?php

$containers = [
    0 => ['id' => '1', 'name' => 'Peta'],
    1 => ['id' => '2', 'name' => 'Epta'],
    3 => ['id' => '3', 'name' => 'Fras'],
    4 => ['id' => '4', 'name' => 'Maxs'],
    5 => ['id' => '5', 'name' => 'Gtay'],
    6 => ['id' => '6', 'name' => 'Prat'],
    7 => ['id' => '7', 'name' => 'Drat'],
];

$invoices = [
    0 => ['id' => '1', 'name' => 'Lebo'],
    1 => ['id' => '3', 'name' => 'Efta'],
    2 => ['id' => '4', 'name' => 'Gadr'],
];

foreach ($containers as $container) {

    foreach ($invoices as $invoice) {

        if (in_array($container['id'], $invoice)) {
            $selected = 'selected';
            break;
        } else {
            $selected = '';
        }
    }

    echo $container['name'] . ' -> ' . $selected . '<br>';
} ?>

Answered By – rmgimenez

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published