How can you filter out specific elements from an array based on their values before displaying the data in a table in PHP?
To filter out specific elements from an array based on their values before displaying the data in a table in PHP, you can use the array_filter function. This function allows you to specify a callback function that determines which elements to keep or remove from the array. Once you have filtered the array, you can then display the remaining data in a table format using HTML.
<?php
// Sample array with data
$data = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Mike', 'age' => 20],
];
// Filter out elements where age is less than 25
$filteredData = array_filter($data, function($item) {
return $item['age'] >= 25;
});
// Display filtered data in a table
echo '<table>';
echo '<tr><th>Name</th><th>Age</th></tr>';
foreach ($filteredData as $row) {
echo '<tr><td>' . $row['name'] . '</td><td>' . $row['age'] . '</td></tr>';
}
echo '</table>';
?>
Keywords
Related Questions
- What changes can be made to the for loop to avoid the "undefined index" notice when accessing the array element?
- What are some best practices for naming classes and methods in PHP to enhance code readability and maintainability?
- How can a PHP developer avoid common mistakes when querying data from databases with PHP?