Tuesday 14 August 2018

How to Remove Empty Elements From An Array in PHP

Sometimes arrays get filled with empty values and we need to remove them.
Here is a function that removes all empty values in an array.
The text is cleaned by HTML if any.
Notes:
  1. There is not a check for duplicate elements.
  2. This function may break UTF-8 strings.
$a[5] = 777;
$a[4] = array(
    1 => 'test3',
    2 => '',
    3 => '',
    4 => 'test2',
    9 => 'test',
    17 => '',
);
$a[9] = 'test';
$a[1] = 111;
$a[2] = 222;
$a[7] = '';
$a['axa'] = 'sfaf';
$a['axgga'] = '';
$a['gsdgsdg'] = 'sfaf';
// Output
array(7) {
  [0]=>
  string(3) "777"
  [1]=>
  array(3) {
    [0]=>
    string(5) "test3"
    [1]=>
    string(5) "test2"
    [2]=>
    string(4) "test"
  }
  [2]=>
  string(4) "test"
  [3]=>
  string(3) "111"
  [4]=>
  string(3) "222"
  ["axa"]=>
  string(4) "sfaf"
  ["gsdgsdg"]=>
  string(4) "sfaf"
}
/**
 * Removes empty values from an array. Also the numeric keys get reordered.
 * If a value is an array the process of cleaning is repeated recursively.
 * Elements start from 1 not from 0 if $non_zero_start is set to 1. Defaults to 0.
 * Values are cleaned by HTML and also by leading/trailing whitespaces.
 *
 * @param array $arr
 * @param bool $non_zero_start if 1 is supplied the array will start from 1
 * @return array
 * @author Svetoslav Marinov <slavi.orbisius.com>
 * @copyright January 2009
 * @license LGPL
 */
function cleanupArray($arr, $non_zero_start = 0) {
    $new_arr = array();
    foreach ($arr as $key => $value) {
        if (!empty($value)) {
            if (is_array($value)) {
                $value = cleanupArray($value, $non_zero_start);

                // If after the cleaning there are not elements do not bother to add this item
                if (count($value) == 0) {
                    continue;
                }
            } else {
                $value = trim(strip_tags($value));
                if (empty($value)) {
                    continue;
                }
            }

            $new_arr[$key] = $value;
        }
    }
    // Reordering elements
    if (!empty($new_arr)) {
        if (!empty($non_zero_start)) {
            $new_arr = array_merge_recursive(array("") + $new_arr);

            // We don't need an empty first element.
            // This was used to shift other elements to start from 1 instead of 0
            unset($new_arr[0]);
        } else {
            $new_arr = array_merge_recursive($new_arr);
        }
    }
    return $new_arr;
}

0 comments:

Post a Comment