DragonVet
DragonVet

Reputation: 409

Trim doesn't seem to work 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.

Upvotes: 3

Views: 1101

Answers (4)

HenchHacker
HenchHacker

Reputation: 1626

Another way using a closure:

$keys = "mavrick, ball,  bouncing, food,  easy mac, ";
$theKeywords = explode(", ", $keys);
array_walk($theKeywords, function (&$item, $key) {
    $item = trim($item);
});
print $theKeywords[2];

But, it will only work in PHP 5.3+

Upvotes: 0

Crisp
Crisp

Reputation: 11447

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));

Upvotes: 3

Ben Lee
Ben Lee

Reputation: 53309

$key gets a copy of the value, not the actual value. To update the actual value, modify it in the array itself (for example, by using a for loop):

$theKeywords = explode(", ", $keys);
for($i = 0; $i < count($theKeywords); $i++) {
    $theKeywords[$i] = trim($theKeywords[$i]);
}
echo $theKeywords[2];

Upvotes: 1

rekire
rekire

Reputation: 47945

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];

Upvotes: 5

Related Questions