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.
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];
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With