-3

I'd like to search an array of products by a specific value and return a sibling value. For example, searching for barcode 4325, should return the ID 2135. What is the best way to do this in PHP?

$products = array(
   array(
    'id' => 2135,
    'title' => 'Product 1',
    'variants' => array(
        'barcode' => '4325',
     ),
   ),
   array(
    'id' => 234,
    'title' => 'Product 2',
    'variants' => array(
        'barcode' => '2355',
     ),
   )
);
user2753924
  • 465
  • 1
  • 5
  • 15

1 Answers1

0

Simple foreach loop

$barcode = '4325';

foreach($products as $value) {
    if ($value['variants']['barcode'] === $barcode) {
        echo 'ID = ' . $value['id'];
        break;
    }
}
Goma
  • 2,018
  • 1
  • 10
  • 19
  • This is a no research, no coding attempt, duplicate and shouldn't be answered. Please remove your answer to show the user that some effort is required. I expect it will be swiftly closed and deleted anyhow. If you delete your answer, the OP can retract the question (saving moderation time) and recover lost rep points. – mickmackusa Nov 29 '17 at 00:07