-1

I have two arrays one contains ids that's going to check if it exists on the second array which is an associative array:

Array 1: [1,2,11, 4]

Array 2:

[["id" => 1, "name" => "abc"], ["id" => 2, "name"=> "xyz"]]

Currently using a nested foreach to iterate over and match them but I wanted to know if there was anything more efficient as the arrays will be a lot larger.

$item = [1,2,11, 4];
$data = [["id" => 1, "name" => "abc"], ["id" => 2, "name"=> "xyz"]];

foreach($items as $item)
{
    foreach($data as $key => $products)
    {
        foreach($products as $product)
        {
            if($product['id'] == $item)
            {
                echo $product['name'];
            }
        }
    }
}

Had a look at this and this but none really fit my scenario.

Any help appreciated.

Abu Nooh
  • 846
  • 4
  • 12
  • 42

3 Answers3

1

array_filter would be an option:

$ids = [ 1, 2, 11, 4 ];

$data = [ [ 'id' => 1, 'name' => 'abc' ], [ 'id' => 2, 'name' => 'xyz' ], [ 'id' => 3, 'name' => 'nono' ] ];

$result = array_filter($data, fn($value) => (in_array($value['id'], $ids)));
lukas.j
  • 6,453
  • 2
  • 5
  • 24
1

You can use array_column() to get all product ids as an indexed array.

Then you can use array_intersect() to fetch the id's that exists in both arrays.

$item = [1,2,11, 4];
$products = [["id" => 1, "name" => "abc"], ["id" => 2, "name"=> "xyz"]];

// Get the ids of all products as an indexed array
$prodIds = array_column($products, 'id');

// Check the id's that exists in both
$existingIds = array_intersect($item, $prodIds);

Demo: https://3v4l.org/HJSoq

Of if you rather do it as a one-liner:

$existingIds = array_intersect($item, array_column($products, 'id'));
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
  • Thank you! How does this or the `array_filter` compare to the nested looping in terms of efficiency and/or cost? – Abu Nooh Mar 26 '22 at 13:54
  • I can't say since I haven't benchmarked it. However, this is two single function calls while the `array_filter()` will call `in_array()` for each product in your list, so if you have 100 products, it will iterate through them and call `in_array()` 100 times. – M. Eriksson Mar 26 '22 at 13:57
-1

You can also use the array_map and the anonymous function.

    $item = [1, 2, 11, 4];
    $products = [["id" => 1, "name" => "abc"], ["id" => 2, "name" => "xyz"]]; 
    
    $result = array_map(function ($row) use ($item) {
       return (in_array($row['id'], $item))?$row:false;
    }, $products);

Result dump:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => abc
        )

    [1] => Array
        (
            [id] => 2
            [name] => xyz
        )

)
emrdev
  • 2,155
  • 3
  • 9
  • 15