Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim doesn't seem to work PHP

Tags:

php


I'm a fan of the function trim in PHP. However, I think I've run into a weird snag. I have the string named keys that contains: "mavrick, ball, bouncing, food, easy mac, " and execute this function

// note the double space before "bouncing"
$keys = "mavrick, ball,  bouncing, food,  easy mac, ";
$theKeywords = explode(", ", $keys);
foreach($theKeywords as $key){
  $key = trim($key);
}
echo $theKeywords[2];

However here, the output is " bouncing" not "bouncing". Isn't trim the right function to use here?

edit:
My original string has two spaces before "bounce", for some reason it didn't want to show up. And I tried referencing it with foreach($theKeywords as &$key) but it threw an error.

like image 966
DragonVet Avatar asked Jun 27 '26 08:06

DragonVet


2 Answers

The problem is that you work with a copy and not the original value. Use references instead:

$theKeywords = explode(", ", $keys);
foreach($theKeywords as &$key){
  $key = trim($key);
}
echo $theKeywords[2];
like image 138
rekire Avatar answered Jun 28 '26 22:06

rekire


You're not re-writing the values in the original array in your loop, you could simplify this to one line, using array_map, like so

$theKeywords = array_map('trim', explode(',', $keys));
like image 22
Crisp Avatar answered Jun 28 '26 21:06

Crisp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!