brmcdani Posted November 11, 2009 Share Posted November 11, 2009 Iam tring to pull a random string out of an array. I have it working but it output's 2 strings and I just want it to output 1. I have tried changing the code up from $keys = array_rand($rand, 2); to $keys = array_rand($rand, 1); but it still won't work. Here is my complete code snippet: $rand = array("asfd", "ghdg", "kfdr", "sdas", "hdsa", "gdsd", "ijko"); $keys = array_rand($rand, 2); echo "Verification letters: "; echo $rand[$keys[0]] . "\n"; echo $rand[$keys[1]] . "\n"; Quote Link to comment https://forums.phpfreaks.com/topic/181170-random-string/ Share on other sites More sharing options...
Daniel0 Posted November 11, 2009 Share Posted November 11, 2009 From the manual: If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. Did you take that into account when switching from 2 to 1? Quote Link to comment https://forums.phpfreaks.com/topic/181170-random-string/#findComment-955811 Share on other sites More sharing options...
brmcdani Posted November 11, 2009 Author Share Posted November 11, 2009 Yeah it says it can "take 1 or more random entries out of an array" I just do not understand why it won't take 1 when I enter in 1 Quote Link to comment https://forums.phpfreaks.com/topic/181170-random-string/#findComment-955823 Share on other sites More sharing options...
Alex Posted November 11, 2009 Share Posted November 11, 2009 You didn't listen to what he said. When grabbing only 1 random key it doesn't return an array. So $keys[0] and $keys[1] are non-existent. If you were only doing one you'd have to do: echo $rand[$keys]; Quote Link to comment https://forums.phpfreaks.com/topic/181170-random-string/#findComment-955835 Share on other sites More sharing options...
salathe Posted November 11, 2009 Share Posted November 11, 2009 You could always force it to be an array: $keys = (array) array_rand($rand, 1); Quote Link to comment https://forums.phpfreaks.com/topic/181170-random-string/#findComment-955842 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.