Filter multidimensional array based on partial match of search value
Use array_filter
. You can provide a callback which decides which elements remain in the array and which should be removed. (A return value of false
from the callback indicates that the given element should be removed.) Something like this:
$search_text = 'Bread';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
For more information:
array_filter
strpos
return values
search a php array for partial string match
You can use preg_grep function of php. It's supported in PHP >= 4.0.5.
$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);
$m_array
contains matched elements of array.
Searching multidimensional arrays for partial value in any key
foreach
again inside the existing foreach
and use strpos() !== false
to check for the $needle
or false
for not found:
foreach($haystack as $key => $array) {
foreach($array as $value) {
if(strpos($value, $needle) !== false) {
return $key;
}
}
}
Search for matching partial values in an array
What you asked me in comment(below my answer),for that you can do it like below (My changed answer):-
<?php
$target = 285;
$array = array('260-315', '285-317', '240-320',"200-285");
foreach($array as $key=>$value){
if($target ==explode('-',$value)[0]){
echo $newTarget = $array[$key];
echo PHP_EOL;
echo $finalTarget = explode('-',$array[$key])[1];
}
}
?>
https://eval.in/702862
Partial match search of an array in PHP
In your stripos() call, you had the needle and haystack reversed.
Then concatenate the result list.
Try this:
function array_find( $needle, $haystack )
{
$result = ''; //set default value
foreach ($haystack as $key => $array) {
foreach ( $array as $key2 => $value ) {
if (false !== stripos($value,$needle)) // hasstack comes before needle
{
$result .= $key . ' ' . $value . ' ' . $key2 . '<br>'; // concat results
//return $result;
}
}
}
return $result;
}
How to filter multidimensional array based on another multidimensional array of exclusions?
Breaking your exclusion array into separate variables is not advisable because this will make your code harder / more tedious to maintain when you want to modify the exclusion list.
Iterate your products array just one time. Inside that loop, loop the attributes in each product having keys which match the first level keys in the exclusion array. This is what array_intersect_key()
does best and this prevents performing an unnecessary comparison on the Product ID
elements. As soon as you find a disqualifying condition to be satisfied, stop the inner loop for best efficiency.
Code #1 (Demo) *my recommendation
$result = [];
foreach ($products as $product) {
foreach (array_intersect_key($product, $exclusions) as $key => $value) {
if (in_array($value, $exclusions[$key])) {
continue 2;
}
}
$result[] = $product;
}
var_export($result);
Code #2: (Demo)
foreach ($products as $index => $product) {
foreach (array_intersect_key($product, $exclusions) as $key => $value) {
if (in_array($value, $exclusions[$key])) {
unset($products[$index]);
break;
}
}
}
var_export(array_values($products));
Code #3: (Demo)
var_export(
array_values(
array_filter(
$products,
function($product) use ($exclusions) {
return !array_filter(
array_intersect_key($product, $exclusions),
function($value, $key) use ($exclusions) {
return in_array($value, $exclusions[$key]);
},
ARRAY_FILTER_USE_BOTH
);
}
)
)
);
Code #4: (Demo)
var_export(
array_values(
array_filter(
$products,
fn($product) => !array_filter(
array_intersect_key($product, $exclusions),
fn($value, $key) => in_array($value, $exclusions[$key]),
ARRAY_FILTER_USE_BOTH
)
)
)
);
Code #1 uses continue 2;
to stop the halt the inner loop, avoid storing the current product in the output array, then return to the outer loop to carry on processing the next product.
Code #2 is directly modifying the $products
array. By unsetting products, the array may cease to be an indexed array (the keys may have gaps between integers). If desirable, call array_values()
after the loop to re-index the output.
Code #3 is using a functional style. It is common for language constructs (e.g. foreach()
) to outperform functional iterators, so I will assume this snippet (and Code #4) will be slightly slower than the first two. Furthermore, array_filter()
doesn't enjoy the early return that the foreach loops have with break
and continue
. In other words, Code #3 & #4 will continue checking against the exclusion array even if a disqualifying condition has already been satisfied for a given product. And if that wasn't enough, I simply find the syntax too convoluted.
Code #4 is the same as Code #3, but is using the slightly shorter "arrow function" syntax which is available from PHP7.4 and up. This affords the omission of use()
and some other characters, but I still find the snippet less intuitive/readable compared to Code #1 & #2.
Filter array elements by searching for partial match in keys and values
Here is a preg_grep
solution that should work more like a WHERE REGEXP 'PATTERN'
in MySQL. I modified Daniel Klein's preg_grep_keys
function to search for the pattern within array keys, and added an array_merge
to it, which should work with the arrays with non-numeric keys. If the keys are numeric, just use a mere preg_grep
solution (preg_grep('~Mark~i', $arr);
to find all array elements having mark
or Mark
, etc.).
array_merge
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
function preg_grep_keys_values($pattern, $input, $flags = 0) {
return array_merge(
array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags))),
preg_grep($pattern, $input, $flags)
);
}
$a = array(
'mark@test.by.com'=> "Mark Mian lv",
'jhon@test.lv.com'=> "John jack lv",
'logon@test.en.com'=> "Bob Logon",
'Stela@test.es.com'=> "Stela Josh",
'json@test.es.com'=> "Json Josh",
'bobby@test.lv.com'=> "Bob Mark"
);
$r = preg_grep_keys_values('~lv~i', $a);
print_r($r);
See this IDEONE demo
The code above searches for lv
(case-insensitively) in the keys first, then in the values, and then merges the results into 1 array. Thus, the results are:
[jhon@test.lv.com] => John jack lv
[bobby@test.lv.com] => Bob Mark
[mark@test.by.com] => Mark Mian lv
How to filter a two dimensional array by value
Use PHP's array_filter function with a callback.
$new = array_filter($arr, function ($var) {
return ($var['name'] == 'CarEnquiry');
});
Edit: If it needs to be interchangeable, you can modify the code slightly:
$filterBy = 'CarEnquiry'; // or Finance etc.
$new = array_filter($arr, function ($var) use ($filterBy) {
return ($var['name'] == $filterBy);
});
Related Topics
Include PHP Inside JavaScript (.Js) Files
How to Prevent Code Injection Attacks in PHP
PHP MySQLi Prevent SQL Injection
Why Does PHP 5.2+ Disallow Abstract Static Class Methods
Reading and Writing Configuration Files
Execute PHP Scripts Within Node.Js Web Server
Reference - Composer Error "Your PHP Version Does Not Satisfy Requirements" After Upgrading PHP
Date Difference in PHP on Days
How to "Echo" a "Resource Id #6" from a MySQL Response in PHP
Sqlstate[Hy000] [2002] Connection Refused Within Laravel Homestead
Disable Warnings When Loading Non-well-formed HTML by Domdocument (PHP)
PHP Login System: Remember Me (Persistent Cookie)
Simple PHP Strpos Function Not Working, Why
Codeigniter Htaccess and Url Rewrite Issues
How to Replace MySQL Functions With Pdo
Are There Good Tutorials on How to Use Pdo