Explanation of PHP Removing Empty Array and Resetting Array Key Name

  • 2021-11-29 23:13:19
  • OfStack

If php is empty, you can use php function array_filter() .


array array_filter ( array [, callback callback] ) 

array_filter() Pass each value in the array array to the callback function in sequence. If the callback function returns TRUE, the current value of the array array is included in the returned result array. The key name of the array is kept unchanged.

If the callback function is not supplied, array_filter() All FALSE entries in array will be deleted. This is the essence of filtering the blank elements of the array.

As shown below:


$entry = array(  
       0 => ' Script House ',  
       1 => false,  
       2 => 1,  
       3 => null,  
       4 => '',  
       5 => 'www.ofstack.com',  
       6 =>'0' 
     );  
print_r(array_filter($entry));  

Output of the above code:

Array
(
[0] = > php stripping empty arrays
[2] = > 1
[5] = > www.ofstack.com
)

As you can see, false, null, and the true "white space" and "0" are all filtered, and the subscript of the array is unchanged.

This leads to a new question, if I want to be right array_filter() What if the key names of the processed new array are serialized to 0, 1, 2 and 3? This is useful in array comparison, so the requirement uses php's sort() Function.


bool sort ( array &array [, int sort_flags] ) 

This function sorts an array. At the end of this function, the array cells will be arranged from the lowest to the highest.

Note: This function gives new key names to cells in array. This will delete the original key names instead of just sorting from scratch.

If you succeed, you will come back to TRUE, and if you fail, you will come back to FALSE.

PHP code


$my_array = array("0" => " Script House  ", "2" => "1", "5" => "www.ofstack.com");  
sort($my_array);  
print_r($my_array);  
?> 

The output results are:

Array
(
[0] = > 1
[1] = > www.ofstack.com
[2] = > This site
)

Summarize


Related articles: