0

when using arrays as parameters in functions, should I pass them by reference or by value? Or there is not that much significance?

2 Answers 2

7

Normally you should pass by value.

You should only pass be reference if you need to modify the array in place, rather than returning a new one.

There's no performance benefit to passing by reference when reading from an array because PHP uses copy-on-write,

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

2 Comments

Indeed, passing by value when you dont need to can cause unexpected changes to the original array if you fiddle with it inside the function.
I think he means passing by reference when you don't need to.
0

If you're interested in maximising performance, do a speed test. Due to PHP optimisations, passing by reference is usually faster than passing by value only if you modify the array (however note the behaviour is also different!).

Passing by value helps reduce the side-effects of a function (side-effects are a common source of code complexity and bugs) and for this and other reasins, it is "better style".

So, pass by reference only if there is a good reason to do so.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.