7

I have a problem when using the trim() function in php.

//Suppose the input variable is null.
$input = NULL;
echo (trim($input));

As shown above, the output of the codes is empty string if the input argument if NULL. Is there any way to avoid this? It seems the trim will return empty string by default if the input is unset or NULL value.

This give me a hard time to use trim as following.

array_map('trim', $array);

I am wondering if there's any way I can accomplish the same result instead of looping through the array. I also noticed that the trim function has second parameter, by passing the second parameter, you can avoid some charlist. but it seems not work for me.

Any ideas? Thanks.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
easycoder
  • 305
  • 2
  • 3
  • 12

2 Answers2

11

Create a proxy function to make sure it's a string before running trim() on it.

function trimIfString($value) {
    return is_string($value) ? trim($value) : $value;
}

And then of course pass it to array_map() instead.

array_map('trimIfString', $array);
Jonah
  • 9,991
  • 5
  • 45
  • 79
4

Why not just:

$input = !empty($input) ? trim($input) : $input;
Mikel
  • 24,855
  • 8
  • 65
  • 66
  • Yes, just realized that. Thanks. – Mikel Feb 12 '11 at 01:46
  • I am used to using `isset()`, because you normally want to treat null and an empty string as equivalent, as you said in your answer. ;-) – Mikel Feb 12 '11 at 01:55
  • Looks like I had things backwards after changing `isset` to `is_null`. Should be fixed now. Let me know if that works. – Mikel May 23 '16 at 00:13