I wrote in my first post about partitions of an integer in PHP that I had just started with PHP and that there were probably better ways to do a few of the lines in the code. Well, having worked with PHP 5 now for a few weeks, I see there are, of course. Specifically, it doesn’t seem worth it to call is_array prior to checking an array’s count as a way to insure the array has really been emptied. Within the context of this function, you are already assuming that was passed in was a proper array and as I mentioned in my first post if you wanted to really check that, you would do so at the top of the function and not each time you operate on the array. Instead, each time you operate on the array you are really worried about whether you have emptied the array by executing the function. In fact, the way I previously posted the function would throw a warning if you have your warnings set to the highest level in php.ini, because it would try to pull a member from an array that was set and not null but which had no members. One other little change, turns out of course that PHP does have a pop function, similar to Perl, so closer to the original Perl I based this on, we can just use array_pop which is a little neater than using array_slice as I had before. So, here is a just-very-slightly cleaned up refactoring of partitions of an integer in PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
See my original post for an example of how to use the function and for links to the algorithm and original Perl implementation I based this PHP translation on.