If the word being searched for is a different case many of the usual array methods will not work when trying to find the match, using preg_grep
however will allow matches to be found in a case-insensitive manner.
function findflavour( $search, $haystack ){
foreach( $haystack as $index => $arr ){
$res=preg_grep( sprintf( '@%s@i', $search ), $arr );
if( !empty( $res ) ) return array_search( array_values( $res )[0], $arr );
}
return false;
}
$search='BaNanA';
$flavours=array(
array( 799390 => 'Banana' ),
array( 799391 => 'Chocolate' ),
array( 729361 => 'Chilli' ),
array( 879695 => 'Apple' ),
array( 995323 => 'Avacado' ),
array( 528362 => 'Orange' ),
array( 723371 => 'Cherry' ),
);
printf( 'Key:%s', findflavour( $search, $flavours ) );
If there might be multiple elements in the source array with the same value but different IDs a slightly different version of the findflavour
function
function findflavour( $search, $haystack, $multiple=false ){
$keys=[];
foreach( $haystack as $index => $arr ){
$res=preg_grep( sprintf( '@%s@i', $search ), $arr );
if( !empty( $res ) ) {
$key=array_search( array_values( $res )[0], $arr );
if( $multiple )$keys[]=$key;
else return $key;
}
}
return $multiple ? $keys : false;
}
$multiple=true;
$search='AVacAdo';
$flavours=array(
array( 799390 => 'Banana' ),
array( 799391 => 'Chocolate' ),
array( 291333 => 'Avacado' ),
array( 729361 => 'Chilli' ),
array( 879695 => 'Apple' ),
array( 995323 => 'Avacado' ),
array( 528362 => 'Orange' ),
array( 723371 => 'Cherry' ),
);
printf( 'Key(s): %s', print_r( findflavour( $search, $flavours, $multiple ), true ) );