Skip to content

Instantly share code, notes, and snippets.

@ADCPD
Created September 28, 2019 16:16
Show Gist options
  • Save ADCPD/a00df3f44b96322fbd6818f216e9d982 to your computer and use it in GitHub Desktop.
Save ADCPD/a00df3f44b96322fbd6818f216e9d982 to your computer and use it in GitHub Desktop.
Filter in array using one or many params
<?php
/**
* If one or more params[] element exists in data[].
* Our function will return the elements conserner
*/
$params = [
"nom" => 'titof',
"prenom" => 'edoe',
"age" => '25'
];
$data = [
0 => [
'nom' => 'john',
'prenom' => 'doe',
'age' => '25'
],
1 => [
'nom' => 'lola',
'prenom' => 'la grandi',
'age' => '72'
],
2 => [
'nom' => 'michael',
'prenom' => 'Pamal',
'age' => '25'
]
];
function getFilteredArray($params, $data) {
$filtredArray = [];
foreach($params as $key => $value) {
foreach($data as $index => $item) {
if(array_key_exists($key, $item) && in_array($value, $params)) {
if($item[$key] == $value ){
$filtredArray[$index] = $item;
} else {
continue;
}
}
}
}
return $filtredArray;
}
var_dump(getFilteredArray($params, $data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment