Monday, September 5, 2022

[FIXED] How can I explode and trim whitespace?

Issue

For example, I would like to create an array from the elements in this string:

$str = 'red,     green,     blue ,orange';

I know you can explode and loop through them and trim:

$arr = explode(',', $str);
foreach ($arr as $value) {
    $new_arr[] = trim($value);
}

But I feel like there's a one line approach that can handle this. Any ideas?


Solution

You can do the following using array_map:

$new_arr = array_map('trim', explode(',', $str));


Answered By - SeanWM
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.