Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Removing empty array elements in PHP
To remove empty array elements in PHP, you can use several approaches. The most common methods include using array_filter() or manually iterating through the array with foreach and unset().
Using foreach and unset()
This method manually iterates through the array and removes empty elements ?
<?php
$my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null);
foreach($my_array as $key => $val) {
if(empty($val)) {
unset($my_array[$key]);
}
}
echo "After removing empty values from the array:<br>";
foreach($my_array as $key => $val) {
echo $my_array[$key] . "<br>";
}
?>
After removing empty values from the array: This 91 102 is a sample
Using array_filter()
The array_filter() function provides a cleaner approach to remove empty elements ?
<?php
$my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null);
// Remove empty elements
$filtered_array = array_filter($my_array);
echo "Original array elements: " . count($my_array) . "<br>";
echo "Filtered array elements: " . count($filtered_array) . "<br><br>";
foreach($filtered_array as $val) {
echo $val . "<br>";
}
?>
Original array elements: 10 Filtered array elements: 6 This 91 102 is a sample
Comparison
| Method | Preserves Keys | Code Length | Performance |
|---|---|---|---|
foreach + unset() |
Yes | Longer | Slower |
array_filter() |
Yes | Shorter | Faster |
Conclusion
Use array_filter() for cleaner, more efficient code when removing empty elements. The foreach approach gives you more control over the removal logic but requires more code.
Advertisements
