Software Development
How To Remove Empty Array Elements in PHP
You can use the PHP array_filter() function to remove empty array elements or values from an array in PHP. This will also remove blank, null, false, 0 (zero) values.
What is array_filter() function?
The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
Remove Empty Array Elements In PHP
Example #1 array_filter() example
<?php $arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0); print_r(array_filter($arr)); // removing blank, null, false, 0 (zero) values ?>
Output:
Array ( [0] => PHP [1] => HTML [2] => CSS [4] => JavaScript )
Example #2 array_filter() example with reindex array elements
we can remove empty value and then reindex array elements. For it we will use array_values() and array_filter() function together.
<?php $arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0); print_r(array_values(array_filter($arr))); ?>
Output:
Array ( [0] => PHP [1] => HTML [2] => CSS [3] => JavaScript )
The array_values() function returns an array containing all the values of an array. The returned array will have numeric keys, starting at 0 and increase by 1.
-
Marketing Tips3 days ago
What is my Instagram URL? How to Find & Copy Address [Guide on Desktop or Mobile]
-
Business Imprint4 days ago
About Apple Employee and Friends&Family Discount in 2024
-
App Development4 days ago
How to Unlist your Phone Number from GetContact
-
News5 days ago
Open-Source GPT-3/4 LLM Alternatives to Try in 2024
-
Crawling and Scraping5 days ago
Comparison of Open Source Web Crawlers for Data Mining and Web Scraping: Pros&Cons
-
Grow Your Business3 days ago
Best Instagram-like Apps and their Features
-
Grow Your Business5 days ago
How to Become a Prompt Engineer in 2024
-
Marketing Tips3 days ago
B2B Instagram Statistics in 2024