Problem:
You have an array which has some values as well as few empty elements (see the following array). You want to remove those empty values from the array.
<?php $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); ?>
Solution:
This is one of the most common problems in everyday programming.
We can solve it in two different methods.
Method 1: Using array_filter() function
<pre> <?php $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); $week_day = array_filter($week_days); print_r($week_day); ?> </pre>
[wpdm_file id=24]
Output: Array ( [0] => Monday [1] => Tuesday [5] => Wednesday [6] => Thursday [7] => Friday [8] => Saturday [9] => Sunday )
How it Works:
The array_filter() function removes all the elements from an array which are equal to boolean FALSE. Empty string is equal to boolean false. So, array_filter() function removes all those empty-string elements and returns elements with values.
Integer 0 or string “0” is also equal to boolean zero. Well, if you like to keep those values in the array, what you’ll do? See the second method-
Method 2: Using array_diff() function
<pre> <?php $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); print_r(array_diff($week_days, array(""))); ?> </pre>
[wpdm_file id=25]
Output:
Array ( [0] => Monday [1] => Tuesday [3] => 0 [5] => Wednesday [6] => Thursday [7] => Friday [8] => Saturday [9] => Sunday )
How it works:
The array_diff() function returns an array which has all the elements of the first array except those are present in the second array. The second array only contains an empty string. So, array_diff() function returns an without any empty string element.
Sort array-keys serially
In the above two examples, you’ve seen that the keys of the removed elements are missing in the resultant array. If you want to serialize the keys, use array_values() function. Let’s rewrite the last example –
<pre> <?php $week_days = array("Monday", "Tuesday", "", "0", "", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); print_r(array_values(array_diff($week_days,array( "" )))); ?> </pre>
[wpdm_file id=26]
Output: Array ( [0] => Monday [1] => Tuesday [2] => 0 [3] => Wednesday [4] => Thursday [5] => Friday [6] => Saturday [7] => Sunday )