-1

Here's some test data in an associative array for which I'm trying to build a trim function:

$header = [ 'comment1' => ' abc ', 'comment2' => 'abc ', 'comment3' => ' abc', 'comment4' => 'abc' ]; 

The foreach line code below works correctly to trim the values within the array and keep the original keys:

echo '<pre>' . print_r($header, 1) . '</pre>'; var_dump($header); foreach ($header as &$val) $val = trim($val); // <--- this is the line that does the trimming echo '<pre>' . print_r($header, 1) . '</pre>'; var_dump($header); 

Outputs:
enter image description here

However, when I attempt to make the foreach into a function like so

function trimValues($array) { foreach ($array as &$value) { $value = trim($value); } } 

And call it like this

echo '<pre>' . print_r($header, 1) . '</pre>'; var_dump($header); trimValues($header); // <--- this is the line that calls the trimming function echo '<pre>' . print_r($header, 1) . '</pre>'; var_dump($header); 

The output shows the trim didn't work
enter image description here

What am I overlooking here?

1
  • 1
    Literally the first line in the accepted answer is your issue : By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. Commented Mar 5, 2022 at 15:15

1 Answer 1

0

Yep, I see the small detail that was overlooked. The & was missing in the first line of the function - function trimValues(&$array) { ...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.