Different ways of removing empty array slots in PHP.
Removing empty array slots in PHP, leaving holes in the array.
A quick way to remove empty elements from an array is using array_filter without a callback function. This will also remove 0s (zeroes) though.
1
|
|
Alternatively, array_diff allows you to decide which elements to keep. The following example will only remove empty strings, but keep 0
1
|
|
Removing empty array slots in PHP, and compacting the array.
Both functions leave ‘gaps’ where the empty entries used to be. You can see it below, where the indices are [1] and [3] and not [0] and [1].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
array_slice can remove those gaps:
1 2 3 4 5 6 7 8 |
|
I haven’t benchmarked it to see whether it is faster than a loop.
Không có nhận xét nào:
Đăng nhận xét