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.

4

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

was waiting for the minimum time to pass, now done :)

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.