-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.

3 Answers 3

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)));
Sign up to request clarification or add additional context in comments.

Comments

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'));

2 Comments

Thank you! How does this or the array_filter compare to the nested looping in terms of efficiency and/or cost?
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.
-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
        )

)

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.