Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - trim array elements value without foreach [duplicate]

Tags:

arrays

php

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?

like image 295
anik4e Avatar asked Dec 09 '22 08:12

anik4e


2 Answers

You can use array_map:

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

Of course this will still iterate over the array internally.

like image 73
Felix Kling Avatar answered Dec 11 '22 10:12

Felix Kling


This should work just fine;

$input = array("     text1","text2      "," text3       ","     text4");
$output = array_map('trim', $input);
var_dump($output);
like image 35
lshas Avatar answered Dec 11 '22 11:12

lshas