How could the code be optimized to improve performance and readability?
The code can be optimized by using a single loop to iterate through the array and checking if the current element is an integer. This will improve performance by reducing the number of loops needed. Additionally, using more descriptive variable names can improve readability.
$numbers = [1, 2, 'three', 4, 'five'];
$filteredNumbers = [];
foreach ($numbers as $number) {
if (is_int($number)) {
$filteredNumbers[] = $number;
}
}
print_r($filteredNumbers);
Related Questions
- What are the best practices for sorting data in PHP arrays based on a specific criteria like status?
- What are the best practices for setting up and troubleshooting PHP form processing on a Linux Ubuntu system using XAMPP?
- How can the performance impact of setting a high value for group_concat_max_len in MySQL be mitigated when dealing with large datasets in PHP applications?