array if empty remove code example

Example 1: php array remove empty values

<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));
//Custom
print_r(array_filter($arr, function ($val) {if ($val > 0) {return true;} else {return false;}}));

Example 2: remove empty array elements php

$colors = array("red","","blue",NULL);

$colorsNoEmptyOrNull = array_filter($colors, function($v){ 
 return !is_null($v) && $v !== ''; 
});
//$colorsNoEmptyOrNull is now ["red","blue"]

Tags:

Php Example