Generate Random Characters in PHP

I searched and looked for this but didn’t find a good solution online: I need to come up with a random alphanumeric string of arbitrary length fast and using least memory. How do you do this in PHP? Most solutions I saw posted would define a set of allowed characters, then iterate arbitrary number of times generating a random number each time that would be mapped to one of the characters. Append to result string every time and you get the result.

That method, even when done efficiently, is very expensive because:

  1. You have to generate a different random number with each iteration
  2. Use a run-time interpreted loop
  3. Map to character
  4. Append to string with every iteration

Then I thought of this:

base_convert(mt_rand(1,pow(36,5)), 10, 36);

What does it do?

Step 1: generates a random number between 1 and 36^5. Why 36^5? Because 36 is 26+10: 26 is for letters a-z, and 10 for numbers 0-9. base_convert function’s max base is 36. Why 5? Because for this example, I wanted to generate random string of max 5 characters in length.

Step 2: converts the resulting random number from 10-base to 36-base, resulting in a random alphanumeric string. No for-loops required.

Now, let’s take this one step further. What if we always wanted to get a result that’s n characters long? Well, creatively set a minimum for mt_rand like this:

$n = 10;
base_convert(mt_rand(base_convert(pow(10, $n-1), 36, 10), pow(36, $n)), 10, 36);

This will generate 10 character alphanumeric strings. Enjoy!

Nokia Going WP7 Not a Surprise

Nokia “picking” Windows Phone for their future is not a surprise. It wasn’t to me, anyway. You don’t pick a former Microsoft big head, Stephen Elop, to lead you anywhere else besides Microsoft. In other words, you don’t buy a screwdriver and expect it to hammer nails.

On a side note, that billion dollar cash deal must spell nice bonuses for some executives. At this point, I’m not entirely sure how serious Nokia executives are about this deal anyway. Nokia Windows phone will not be out for at least another year, which is an eternity in mobile world these days; and, in the meantime, they have to hold on to Symbian, which they will soon phase out; and, start over with Windows. It will be like a giant corporation in a startup company mode. One word – disaster.

Amazon Planning Android Kindle?

Amazon it planning to launch an Android tablet device. There is no other way around it. Why? Because there is no reason for Amazon to launch their Android app store otherwise. There is no incentive for them to do favors to Google, or to any of Android tablet manufacturers, which are also Amazon’s competitors, by the way.

The only real reason to establish the Android app store is to create an “ecosystem” (yes, I did use that buzzword) where their next Kindle would naturally fall in place.