0

I have this in PHP:

$_chars = "0123456789ZXCVBNMASDFGHJKLQWERTYUIOP";

for($l = 0; $l<4; $l++){
    $temp = str_shuffle($_chars);
    $_charcode .= $temp;
}

I want it to only generate 4 characters. Currently It's generating 6. I've tried editing $l but it doesn't change anything.

1
  • 1
    str_shuffle returns the whole string, not just one character. You're actually getting a 144 character (4 * 36) string. Commented Oct 10, 2013 at 18:06

2 Answers 2

2

Docs (http://php.net/str_shuffle) state:

str_shuffle() shuffles a string. One permutation of all possible is created.

it should actually generate 4 * strlen($_chars) characters…

I assume you want:

$_charcode .= $temp[0]; // only one character
Sign up to request clarification or add additional context in comments.

Comments

1

From the documentation:

str_shuffle() shuffles a string. One permutation of all possible is created.

You'll want to retrieve just one character from the shuffled string:

$_charcode .= $temp[0];

So, the code should look like:

$_chars = "0123456789ZXCVBNMASDFGHJKLQWERTYUIOP";

$_charcode = ''; // initialize the variable with an empty string
for($l = 0; $l<4; $l++){
    $temp = str_shuffle($_chars);
    $_charcode .= $temp[0];
}
echo $_charcode;

Output(example):

8VG6

Demo!

3 Comments

lol :o) You edited your question to reflect the same content as I have (and a little bit more)
@bwoebi: Nope, I didn't. I just added the documentation bit (I can't create one excerpt of my own). Also, look at the timestamp of the answers.
I seemed to me this way; sorry then ;-) The timestamp has a difference of 7 seconds, but you had also edited in the five minutes after creation while I hadn't…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.