Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php in_array between 2 arrays

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>';
} ?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading