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:
- There is not a check for duplicate elements.
- This function may break UTF-8 strings.
[code]
$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';
[/code]
// Output
[code]
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"
}
[/code]
[code]
/**
* 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
* @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;
}
[/code]
Related:
Hi,
Ugh, I liked!
Thank you
Rufor
I am glad you like stuff :D
Better way to do this:
$sweepedArray = array_filter($dirtyArray);
Better to use array_filter().
e.g.
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
print_r(array_filter($entry));
?>
output:
Array
(
[0] => foo
[2] => -1
)
Sanjay didn't see what Andrew said a year before him :-)
However, both of them didn't mention that this function - array_filter - is useful for a single array, not for multidimensional array.
Take a look at the description ot php.net also:
http://php.net/manual/en/function.array-filter.php
One useful thing is that you can use a callback function to filter the arra not just for empty values, but for the result defined in that callback function.
Very useful thing!
Thanks Niki for the comment fellow Bulgarian :)