Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the empty values of an array without removing the keys and also without resetting the keys

Tags:

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?

like image 615
Programmer Avatar asked Jun 07 '18 09:06

Programmer


People also ask

How do you remove an empty value from an array?

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.

How do you remove an array from a key?

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.

Is PHP an 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.


1 Answers

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
)
like image 74
Eddie Avatar answered Sep 28 '22 18:09

Eddie