1

I have some question about searching a value in multidimensional array. This is my code

$groep = array(
                1 => array("111","222"),
                2 => array("333","444")
                );
$groepje = 0;
foreach($groep as $row => $value){
    if(array_search($serial,$value)){
        $groepje = $row;
    }
}

Now i want to set $groepje to the 'head'key of the array, so if $serial = 111 it have to give back 1, if $serial = 444 it have to give back 2.

What i do get is the wrong number, so 0 if its 111 or 333.

Can someone tell me what i'm doing wrong?

Thanks!

  • 1
    Where is `$serial` defined? – ficuscr Sep 23 '20 at 18:16
  • Does this answer your question? [PHP Multidimensional Array Searching (Find key by specific value)](https://stackoverflow.com/questions/8102221/php-multidimensional-array-searching-find-key-by-specific-value) – ficuscr Sep 23 '20 at 18:17

1 Answers1

0
  • You can use in_array to search for the specified serial.
  • I renamed some of your variables to make it clearer.
  • Used break to break out of the loop once we know we've found what we're looking for.
  • assuming you define $serial above your foreach

http://sandbox.onlinephpfunctions.com/code/ca34f236ca2d19af8c098120de1707f14bed285a

<?php

$groep = array(
    1 => array("111","222"),
    2 => array("333","444")
);

$groepje = 0;
$serial= '333';

foreach($groep as $key => $data) {
    
    if (in_array($serial, $data)) {
        $groepje = $key;
        break;
    }
}

// 2
echo $groepje;
waterloomatt
  • 3,444
  • 1
  • 18
  • 24