PHP removes the null, null key / values ​​of an Array, keeping the key / values ​​otherwise not null / null

I have an array that received about 12 potential key / value pairs. It is based on _POST / _GET

The keys are not numeric, as in 0-n, and I need to store the keys where applicable. My problem is that I know that sometimes a key will be passed where the value is null, empty or equal to "". In case I want to trim these keys before processing the array. As it runs down the line, there is not something that will break my script.

Now, some time ago, I either did or found this function (I don’t remember what it was in my arsenal for a while, at least).

function remove_array_empty_values($array, $remove_null_number = true) { $new_array = array(); $null_exceptions = array(); foreach($array as $key => $value) { $value = trim($value); if($remove_null_number) { $null_exceptions[] = '0'; } if(!in_array($value, $null_exceptions) && $value != "") { $new_array[] = $value; } } return $new_array; } 

What I would like to do is very similar to this, however it works well with arrays that can have nn key values, and I am not dependent on the key, as well as on the value, to determine what is where, when. As stated above, you just delete everything and then just restore the array. Where I am stuck, trying to figure out how to simulate the above function, but where I save the keys I need.

+6
source share
4 answers

If I understand correctly what you need, you can use array_filter() or you can do something like this:

 foreach($myarray as $key=>$value) { if(is_null($value) || $value == '') unset($myarray[$key]); } 
+11
source

If you want to quickly remove NULL, FALSE and Empty Strings (""), but leave the values ​​0 (zero), you can use the standard php strlen function as a callback function:

 // removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values $result = array_filter( $array, 'strlen' ); 

Source: http://php.net/manual/en/function.array-filter.php#111091

+6
source

array_filter is a built-in function that does exactly what you need. At best, you will need to provide your own callback, which will decide which values ​​remain and which are deleted. Keys are saved automatically as described in the function description.

For instance:

 // This callback retains values equal to integer 0 or the string "0". // If you also wanted to remove those, you would not even need a callback // because that is the default behavior. function filter_callback($val) { $val = trim($val); return $val != ''; } $filtered = array_filter($original, 'filter_callback'); 
+4
source

use +1 with your key variable to skip the null key in the array

 foreach($myarray as $key=>$value) { echo $key+1; //skip null key } 
0
source

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


All Articles