Initial PHP Array Index Index Values

How to trim PHP array and remove all empty indexes

Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => 4 [8] => 6 [9] => ) 

The output should look like

  Array ( [0] => 4 [1] => 6 ) 
+4
source share
3 answers

You are looking for the array_filter function; -)


For example, this piece of code:

 $arr = array(null, 0, null, 0, '', null, '', 4, 6, '', ); $arr_filtered = array_filter($arr); var_dump($arr_filtered); 

It produces the following result:

 array 7 => int 4 8 => int 6 

Please note that all false values ​​have been deleted.


And if you want to be more specific, you can specify your own filter function. For example, to remove only null from an array, I could use this:

 function my_filter($item) { if ($item === null) { return false; } return true; } $arr = array(null, 0, null, 0, '', null, '', 4, 6, '', ); $arr_filtered = array_filter($arr, 'my_filter'); var_dump($arr_filtered); 

And I get:

 array 1 => int 0 3 => int 0 4 => string '' (length=0) 6 => string '' (length=0) 7 => int 4 8 => int 6 9 => string '' (length=0) 
+9
source

Here's another way:

 <?php $array = array( 0 => 0, 1 => , 2 => '', 3 => 4, 4 => 6, 5 => null ); foreach( $array as $a ) { if( !empty($a) AND $a != NULL AND $a != 0 ) // NULL, 0 { $new_array[] = $a; } } print_r( $new_array ); ?> 

The output will be:

 Array ( [0] => 4 [1] => 6 ) 
+2
source

I like the homework.

I would advise you to take a look at the array_filter function. This is the most suitable option.

+1
source

Source: https://habr.com/ru/post/1303716/


All Articles