Jump to content

How to get all the letters in random order?


tibberous

Recommended Posts

I am trying to get the 26 letters of the alphabet as an array in random order.

 

Sounds easy right?

 

I've been at it 45 minutes - still doesn't work:

 

function random_letters(){
	$letters = array();

	for($i=0;$i<26;$i++){
		$letters[$i] = chr($i+97);
	}


	$retval = array();

	for($i=0;$i<26;$i++){
		$indexes = array_keys($letters);
		$index = array_slice($indexes, $index = floor(rand(0,count($indexes))), 1);
		$index = $index[0];

		$retval[$i] = $letters[$index];
		$retval[$i] = $retval[$i][0];
		unset($letters[$index]);
	}



	return $retval;
}

 

I've decided to say hell with it and just make a database with the 26 letters, then use "select * from letters order by rand()"

 

But I'd like to see it done with php.

 

Only rule is you can't use usort.

 

 

Link to comment
Share on other sites

I think this would work:

$string = 'someword';
$letter_array = explode('', $string);
shuffle($letter_array);
$string = '';
foreach($letter_array AS $letter){
$string .= $letter;
}
echo $string;

Might be a better way?

Link to comment
Share on other sites

Slightly better, as it does away with an unnecessary loop and explode call:

$lettersArray = range ('a', 'z');
shuffle ($lettersArray);
$lettersRand = implode ('', $lettersArray);

Yup, I totally forgot implode. xD

Link to comment
Share on other sites

Not sure if I agree with that statement, as it introduces a totally unnecessary HTTP call. For something that is done in 2 or 3 lines of PHP, as shown above. (I take it you actually tried my code?)

Not to mention all of those who either have JS turned off or using browser that doesn't support JS/AJAX. They won't be getting your randomized letters at all, if you're relying upon JS/AJAX.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.