Often, when dealing with multidimensional data, it becomes necessary to filter specific values. Filtering a two-dimensional array by name key is a common scenario.
PHP's powerful array_filter function can be employed to perform this operation. It takes an array and a callback function as input. The callback function evaluates each element of the input array and returns true or false, indicating whether that element should be included in the resulting filtered array.
In our case, we want to filter the array by the name key. The following callback function checks if the name key of the array element matches the desired value:
$searchValue = 'CarEnquiry'; // Change this to the desired name value $callback = function ($var) use ($searchValue) { return ($var['name'] == $searchValue); };
This callback function can then be passed to array_filter:
$filteredArray = array_filter($inputArray, $callback);
The original requirement specified a fixed search value, but it's common to allow interchangeable values. To achieve this, the callback function can be modified:
$filterBy = 'CarEnquiry'; // Current filter value $callback = function ($var) use ($filterBy) { return ($var['name'] == $filterBy); };
By passing this callback to array_filter, we can filter the array based on the specified $filterBy variable.
The above is the detailed content of How to Filter a Two-Dimensional Array in PHP by a Specific Value?. For more information, please follow other related articles on the PHP Chinese website!