Check if object is in (multidimensional) array?

Python:

>>> arr = [[1,3],[2,4]]
>>> 2 in [x[0] for x in arr]
True
>>> 3 in [x[0] for x in arr]
False

PHP:

$arr = [[1,3],[2,4]];
var_dump(in_array(1, array_map(function($x){return $x[0];},$arr), true));
var_dump(in_array(3, array_map(function($x){return $x[0];},$arr), true));

Gives

bool(true)
bool(false)

Adding true for “strict mode”, to prevent false positives (1 == true, 0 == false)

Java:

int[][] arr = {{1,3},{2,4}};
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(1));
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(3));

Gives

true
false

Leave a Reply

Your email address will not be published. Required fields are marked *