How to Search Array for Multiple Values in PHP

How to search Array for multiple values in PHP?

You want array_keys with the search value

array_keys($list[0], "2009-09-09");

which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...

$uniqueKeys = array_unique($list[0])

foreach ($uniqueKeys as $uniqueKey)
{
$v = array_keys($list[0], $uniqueKey);

if (count($v) > 1)
{
foreach ($v as $key)
{
// Work with $list[0][$key]
}

}
}

Using array_search for multi value search

is there a way to search using multiple values: eg. get key where
name='flash' && type='camera' ?

Simply with array_keys function:

$result_key = array_keys($array_subjected_to_search, [ 'type' => 'camera','name' => 'flash']);
print_r($result_key);

The output:

Array
(
[0] => 3
)

How do I to get multiple key with array_search()?

Boring solution using a foreach loop:

function get_in_array( string $needle, array $haystack, string $column){
$matches = [];
foreach( $haystack as $item ) if( $item[ $column ] === $needle ) $matches[] = $item;
return $matches;
}

Using array_filter:

function get_in_array( string $needle, array $haystack, string $column ){
return array_filter( $haystack, function( $item )use( $needle, $column ){
return $item[ $column ] === $needle;
});
}

How to use array_search for searching values from multiple values in an array

Assuming that your $DATA is actually the JSON source, and that you've edited some of it out and left a dangling comma, then this code will find you the lowest index at which one of the values in $CODES appears. Note that you have to search for values individually, as array_search will otherwise look for the array as a value to match.

$DATA = json_decode($json, true);
$CODES = array("0011","003");
$SEARCH_KEY = count($DATA['SCANS']);
foreach ($CODES as $CODE) {
$SEARCH_KEY = min($SEARCH_KEY, array_search($CODE,array_column($DATA['SCANS'],"SCAN_CODE")));
}
echo $SEARCH_KEY;

Output (for your data):

1

Demo on 3v4l.org

If you want to find the scan with the earliest SCAN_TIME which matches one of the codes, you can sort the SCANS and then get an index into the sorted array e.g.

$DATA = json_decode($json, true);
$CODES = array("0011","003");
$SEARCH_KEY = count($DATA['SCANS']);
$SCANS = $DATA['SCANS'];
array_multisort(array_column($SCANS, 'SCAN_TIME'), $SCANS);
print_r($SCANS);
foreach ($CODES as $CODE) {
$SEARCH_KEY = min($SEARCH_KEY, array_search($CODE,array_column($SCANS,"SCAN_CODE")));
}
print_r($SCANS[$SEARCH_KEY]);

Output (for my changed data in this demo):

Array
(
[SCAN_TIME] => 2019-07-19 00:22:00
[SCAN_STATUS] => Scanned
[SCAN_CODE] => 003
[SCAN_LOCATION] => GAX
)

check multiple values using in_array in PHP

You need to use array_intersect() to see what values are in both arrays. in_array() checks to see if one value exists in an array so that won't work for you (unless you use a loop to iterate through your $tempRecordTypes array and compare it to the $allRecordTypes array).

$RecordType = array_intersect($tempRecordTypes,$allRecordTypes);

How to search a multi-dimensional array by multiple values at once in PHP?

You can build your search query as an array and compare the intersection of each item with it.

$search = ['score' => '50', 'name' => 'Bob'];

foreach($data_info_array as $k => $v) {
if ( $search === array_intersect($v, $search) ) {
echo $k;
break;
}
}

@mickmackusa noticed it is safer to use array_intersect_assoc() here. He's right because when the multi-dimensional array items are unpredictable, nothing forbids to have items like that:

['miaou' => '50', 'graou' => 'Bob', 'score' => '50', 'name' => 'Bob']

where the searched values are also present but for other keys. In this case array_intersect() returns all correct values (with their corresponding keys of course) regardless the keys in $search, and the comparison with the search array will return false.

But using array_intersect_assoc(), you ensure that only values for keys in $search are taken in account.

Conclusion: If you let yourself be lulled into sleep by the seeming monotony of multidimensional array items, you won't be immune to surprise when unexpected variations arise.

Array search multiple values in consecutive order

Good effort people, I admit the request was slightly hard to explain - so didn't get exactly what I was looking for. I realised that what I wanted was essentially an array_search that returns multiple keys when the needles are found consecutively. I've gone ahead and made the function myself:

/**
* Search for consecutive needles in haystack and return the corresponding keys.
*
* @param array $needles => Array values.
* @param array $haystack => Array to search.
* @param int $searchDirection => [0] (forwards) | [1] (backwards).
* @return array
*/
function array_search_all_consec(array $needles, array $haystack, $searchDirection = 0)
{
$needlesInScope = array_values($needles); // Keys not relevant, reset them.
$haystackInScope = $haystack;

if (in_array(reset($needlesInScope), $keys = array_keys($haystackInScope))) {
$needlesLength = count($needlesInScope);

foreach (($searchDirection == 0 ? $keys : array_reverse($keys)) as $offset) {
$length = $offset + $needlesLength;
$sliced = array_slice($haystackInScope, $offset, $length);

if (empty(array_diff_assoc($needlesInScope, $sliced))) {
return range($offset, $length - 1);
}
}
}

return [];
}

Test 1

$o = [
0 => "hello",
1 => "i",
2 => "like",
3 => "cats",
4 => "they",
5 => "cute",
6 => "and",
7 => "cuddly",
8 => "you",
9 => "know",
10 => "well",
11 => "i",
12 => "love",
13 => "cats",
];

$s = [
"i",
"love",
"cats",
];

return array_search_all_consec($s, $o);

// Result
array(3) {
[0] =>
int(11)
[1] =>
int(12)
[2] =>
int(13)
}

Test 2

$s = [
"i",
"like",
"cats",
];

return array_search_all_consec($s, $o);

// Result
array(3) {
[0] =>
int(1)
[1] =>
int(2)
[2] =>
int(3)
}

Test 3

$s = [
"i",
"lov3",
"cats",
];

return array_search_all_consec($s, $o);

// Result
array(0) {
}

Test 4

$s = [
"cats",
"i",
"love",
];

return array_search_all_consec($s, $o);

// Result
array(0) {
}

Test 5

$s = [
"i",
"love",
"cats",
"blah",
];

return array_search_all_consec($s, $o);

// Result
array(0) {
}


So there you have it. If anyone can improve the efficiency of the function please do contribute!

how can a find multiple values at once in an array php

I agree that with such a small number of possible combinations to win, the solution can be kept very simple. I would do it using array_diff.

function has_won($user) {
// returns false if the user has not won, otherwise
// returns the first winning combination found.
$wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
foreach ($wins as $win) {
if (!array_diff($win, $user)) return $win;
// array_diff returns the values in the first argument
// not present in any subsequent arguments. So if its
// result is empty, the user has winning combination.
}
return false;
}

PHP Checking multiple values in an array - the right way?

You can do it something like this.

Solution 1:
Here we are using array_intersect for checking common values between two arrays.

<?php

ini_set('display_errors', 1);
$valuecheck = false;
$daafids=array(96,97,99,122,123,124,125,126,127,128,129,130,131,132,133);
if(count(array_intersect($prodcat, $daafids))>0)
{
$valuecheck=true;
}

Here we are using in_array to search that particular element in the array.

Solution 2:

<?php

ini_set('display_errors', 1);
$valuecheck = false;
$daafids=array(96,97,99,122,123,124,125,126,127,128,129,130,131,132,133);
foreach ($prodcat as $daafid) {
if(in_array($daafid,$daafids)){
$valuecheck=true;
break;
}
}
if ($valuecheck == true) {
echo $text_true;
}

PHP check if array contains multiple values

If you are only getting one column from the database, and you use PDO, I would suggest you use the fetch mode FETCH::COLUMN, to gain an array that looks like

$arr = [1, 2];

Then you can simply use in_array to check for the value



Related Topics



Leave a reply



Submit