In PHP, how can a search for entries in an array with composite keys be elegantly solved?
When searching for entries in an array with composite keys in PHP, one elegant solution is to use array_filter() with a custom callback function. This function can iterate through the array and check if the composite key matches the search criteria. The callback function should return true for matching entries and false for non-matching entries.
// Sample array with composite keys
$array = [
['key1' => 'value1', 'key2' => 'value2'],
['key1' => 'value3', 'key2' => 'value4'],
['key1' => 'value5', 'key2' => 'value6']
];
// Search criteria for composite keys
$searchKey1 = 'value3';
$searchKey2 = 'value4';
// Custom callback function for array_filter
$result = array_filter($array, function($entry) use ($searchKey1, $searchKey2) {
return ($entry['key1'] == $searchKey1 && $entry['key2'] == $searchKey2);
});
// Output the matching entries
print_r($result);
Keywords
Related Questions
- What are some alternative methods, such as using sessions or hidden fields, to manage a delay before redirection in PHP?
- In the context of PHP development, why is it recommended to compare the username and password directly in MySQL rather than retrieving and comparing them separately in PHP code?
- How can PHP 4 syntax, like using "var", be updated to PHP 5 standards for class properties?