0

PHP manual says you have to do sort($array). $array will be passed by reference, so sort() will modify $myArray.

I'm just wondering if there is any problem or implication if you do sort(&$myArray).

Gumbo
  • 643,351
  • 109
  • 780
  • 844

2 Answers2

1

The short answer is it won't make a difference.

The long answer is that you should avoid references at all cost. They are a major source of bugs, and you really don't need them. There are a few rare occurrences where references are needed to solve a problem, but they are very few and very far between.

The reason there are a lot of references, is prior to PHP 5.0, there was no concept of object references. So you needed to pass all objects by reference (and return them by reference) to get any kind of OO functionality (allow methods to modify the object, etc). But since 5.0 (which is a decade old), that's no longer needed. To understand how it works now, I'd suggest reading this answer.

So do the more maintainable and correct usage:

sort($myArray);
Community
  • 1
  • 1
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • Thanks for your answer. I know what references involves. I'm training for the Zend PHP Certification and I'm just looking for every single detail. I know I have to avoid pass-by-reference everytime it's possible. Calling sort(&$myArray) modify in any way $myArray in a different way it's modify by calling sort($myArray)? – Jose Duenas Sep 01 '11 at 19:32
1

To give a more detailed answer:

  • It'll work without issues in PHP 5.2 and before.
  • It'll trigger an E_DEPRECATED warning (sometimes) on PHP 5.3
  • It is very likely to stop working on PHP 5.4. (Which alternates between refusal and memory violation errors. Not finalized yet, but that change is likely to stay.)

The reasoning for deprecating pass-by-references is diffuse. It's mostly code-cleanliness. Secondly it was commonly misused by newcomers, leading to side-effects if unsupervised. (If newcomer misuse ever was a good reason for deprecation, then mysql_query should have been long gone.)
And thirdly, there are in fact some internal memory management issues with passing parameters by reference when the ZendVM does not expect it. (Quercus and Project Zero do not have such issues.)

mario
  • 144,265
  • 20
  • 237
  • 291