Click to See Complete Forum and Search --> : PHP trim array function


skywalker2208
10-17-2008, 11:05 AM
I could have sworn there was a function to be used on arrays that would remove all empty elements. I know it isn't called trim, but I thought I have seen it before, but can't find it. Maybe I am imagining things. This is what I am looking for it to do.

$test_array('foo', 'bar', '', 'sleep', '');

after going through the function it the array would be

$test_array('foo', 'bar', 'sleep');

I know writing a function isn't that hard and I come across needing this at different times for different sites so I was just wanting to know if somebody else knows if this function exists.

skywalker2208
10-17-2008, 11:11 AM
Found it.

scragar
10-17-2008, 11:13 AM
there isn't a built in function (check for yourself if you don't believe me: http://php.net/array ), but you can make one:
function array_trim($ar){
foreach($ar as $key)
if(empty($ar[$key]))
unset($ar[$key]);
return $ar;
};
which will work like:

$test = Array('foo', 'bar', '', 'sleep', '');
var_dump($test);
echo "\n<br>\n";
var_dump(array_trim($test));
or you could get it to work by ref, which would be better:
function array_trim(&$ar){
foreach($ar as $key)
if(empty($ar[$key]))
unset($ar[$key]);
};Choice is yours.

skywalker2208
10-17-2008, 11:42 AM
I found this thread
http://www.webdeveloper.com/forum/showthread.php?t=185855

SyCo
10-17-2008, 05:27 PM
Did you see the use notes on the man page?
http://us.php.net/manual/en/function.array-filter.php

It looks like you're using alpha values in your array but be aware it'll remove anything that factors to false or zero. If that what you want then cool.

NogDog
10-17-2008, 07:10 PM
Did you see the use notes on the man page?
http://us.php.net/manual/en/function.array-filter.php

It looks like you're using alpha values in your array but be aware it'll remove anything that factors to false or zero. If that what you want then cool.

And if that's an issue, you can use the optional callback function parameter to tailor its functionality to exactly what you need.

SyCo
10-17-2008, 07:23 PM
yea, just wanted to bring it to attention. It's a neat function.

skywalker2208
10-17-2008, 08:54 PM
It works like a charm. Great function.