anonymous
anonymous

Reputation: 127

Filter 2d array to keep all rows which contain a specific value

I have a two dimensional haystack array like this:

[
    4 => [0, 1, 2, 3, 10],
    1 => [0, 1, 2, 3, 10],
    2 => [0, 1, 2, 3],
    3 => [0, 1, 2, 3]
]

Let's say that I have a search value of $x = 10.

How can I search in above array and get an array index which contains $x.

In my current example, subarrays with key 4 and 1 contain value of $x -- I need those 2 subarrays.

Upvotes: 0

Views: 5796

Answers (5)

Syscall
Syscall

Reputation: 19764

You can use array_filter() to keep only the array that contains the value you want:

$array = [
    [0, 1, 2, 3, 10],
    [0, 1, 2, 3, 10],
    [0, 1, 2, 3],
    [0, 1, 2, 3]
];

$x = 10;
$out = array_filter($array, function($row) use($x) {
    return in_array($x, $row);
});
print_r($out);

Output:

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 10
        )

    [1] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 10
        )
)

In modern PHP (from PHP7.4), "arrow function" syntax can be used:

$x = 10;
var_export(
    array_filter($array, fn($row) => in_array($x, $row))
);

Upvotes: 4

Vishvakarma Dhiman
Vishvakarma Dhiman

Reputation: 86

You can use array_search() function to search the value in array..

Link: http://php.net/manual/en/function.array-search.php

For Exp:

$x = 10; // search value 
$array = array(...); // Your array 
$result = array(); // Result array 
foreach ($array as $key => $value) 
{ 
   if (array_search($x, $value)) 
   { 
      $result[] = $array[$key]; // push the matched data into result array.. 
   }
}

print_r($result);

Upvotes: 1

mooga
mooga

Reputation: 3317

You can use as well in_array

$array = array(); // Your array
$x = 10;
$result = array(); // initialize results

foreach ($array as $key => $value) {
    if (in_array($x, $value)) {
        $result[] = $array[$key]; // 
    }
}

print_r($result)

Upvotes: 2

Luffy
Luffy

Reputation: 1026

You could loop then use array_search()

$array = array(...); // Your array
$x = 10;

foreach ($array as $key => $value) {
    if (array_search($x, $value)) {
        echo 'Found on Index ' . $key . '</br>';
    }
}

Or if you need the arrays with those index

$array = array(...); // Your array
$x = 10;
$result = array(); // initialize results

foreach ($array as $key => $value) {
    if (array_search($x, $value)) {
        $result[] = $array[$key]; // push to result if found
    }
}

print_r($result);

Upvotes: 3

Marko Paju
Marko Paju

Reputation: 312

You can use array_search();

doc: http://www.php.net/manual/en/function.array-search.php

Upvotes: 0

Related Questions