How to remove the empty values of an array without removing the keys and also without resetting the keys.
Eg:
[0]= "test1"
[1]= ""
[2]= "test2"
Doing array_filter results in the following output:
[0]= "test1"
[2]= "test2"
Here the key is also removed. Is there a way to remove only the values without removing the keys to get an output like :
[0]= "test1"
[1]= "test2"
Is there any php function that does it?
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.
You can use array_values
to get all the values from the array and indexes the array numerically.
$arr = array("test1","","test2");
$result = array_values( array_filter( $arr ) );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => test1
[1] => test2
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With