1

I have an array with the following setup:

array(
 array(
  'product_id' => 733
 ),
 array(
  'product_name' => Example
 )
)

I want to check that 733 exists in my array which I need to use array_search (going by googling) as in_array doesn't work on m-d arrays.

My code is:

$key = array_search( '733', array_column( $items, 'product_id' ) );

If I var_dump the $items array I can see the product_id

I want to check the specific ID exists in the array and then perform other code.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Gareth Gillman
  • 343
  • 1
  • 4
  • 20

1 Answers1

1

So basically you want to check that given product-id exist in your multidimensional array or not?

You can do it like below:-

<?php

$items = array(
 array(
  'product_id' => 733
 ),
 array(
  'product_name' => Example
 )
);
function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if (!empty($val['product_id']) && $val['product_id'] == $id) {
           return "true"; // or return key according to your wish
       }
   }
   return "false";
}
echo $found = searchForId(733, $items);

Output:- https://eval.in/805075

Reference taken:- https://stackoverflow.com/a/6661561/4248328

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98