4

I am using following code in php: Code:

$input = array("     text1","text2      "," text3       ","     text4");
$output = array();
foreach($input as $val)
     {
        $output[] = trim($val);
     }
var_dump($output);

Is it possible to trim array elements value without foreach loop?

anik4e
  • 493
  • 8
  • 16
  • No. trim accepts only strings as its argument. One way or another, you're going to have to loop over the array. – Marc B Apr 22 '14 at 19:25

3 Answers3

11

You can use array_map:

$output = array_map('trim', $input);

Of course this will still iterate over the array internally.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

This should work just fine;

$input = array("     text1","text2      "," text3       ","     text4");
$output = array_map('trim', $input);
var_dump($output);
lshas
  • 1,691
  • 1
  • 19
  • 39
1

use array_map for apply a function to each element

$input = array_map('trim', $input);
Maks3w
  • 6,014
  • 6
  • 37
  • 42