shuffle() or: How I Learned to Stop Worrying and Love PHP

I have said some not very nice things about PHP on this blog, and I’m sure over time I’ll be adding more such criticisms. This time I’d like to highlight a handy little feature in PHP, one that is a great deal easier to use than it’s Java counterpart.

Shuffling the elements in an array is probably a programming exercise in every single 1st year computer science textbook, it’s easy enough to do, but because it’s been done roughly 100 million times before, it feels moronic doing it again. So it’s nice when programming languages offer it as standard language functionality. PHP does by way of the shuffle() function and Java does by Collections.shuffle() static method. Seems simple enough, except that an array is not a collection in Java. So you can’t take your int[] and shuffle the elements quite so easily.

If you have an Integer[] in Java you can just pass it into Arrays.asList(array), get the collection and shuffle it. Uh oh, I said Integer[] which sadly is not the same as an int[]! So the difference between the two means I’m going to need to convert all the elements of the int[] into a Integer[] before I can shuffle it, geez, if I have to iterate the list once to convert type, I may as well just not put them back where I found them!

So this is me admitting there is an advantage to a dynamic language. I maintain I’d still rather pay the upfront cost of a few extra lines of code here-and-there for type safety, try getting a PHP IDE to reliably autocomplete instance methods for you, when it doesn’t know the type of a variable! Perhaps I need to start using Eiffel

You might also be interested in:

  1. PHP 1, Java 0: The method assertEquals(Object, Object) is ambiguous for the type
  2. My list of PHP language features with hard-to-imagine-use-cases: #1 – The @ symbol that supresses errors
  3. Taking GWT 1.5 RC1 for a spin – a review of the new GWT release candidate.


Tagged as , , , + Categorized as Language Design, PHP

Leave a Comment

Name:

Email:

Website:

Sporadic Tweeting...

  • My Top 3 Weekly #lastfm artists: The Black Keys (86), Mos Def (9) and Foo Fighters (8) http://bit.ly/c6eW5I 4 days ago
  • Finally beaten the 'Invalid package.xml format' fluff when trying to upload to Magento Connect - latest SMTP finally available there - yah! 4 days ago
  • My latest post includes a guide to making a basic extension too, so if you're just starting out with Magento extensions, check it out. 5 days ago
  • More updates...

What I'm listening to

  • The Black Keys - Brothers
  • Mos Def - Black On Both Sides
  • Foo Fighters - Skin and Bones
  • The Black Keys - Chulahoma
  • The White Stripes - Icky Thump
  • The Naked and Famous - This Machine
  • The Black Keys - The Moan
  • Red Hot Chili Peppers - Blood Sugar Sex Magik
  • Fat Freddys Drop - Based on a True Story