using chr + rand to generate a random character (A-Z)












8















I'm using the following to generate a random character from A-Z, but it's occasionally generating the @ symbol. Any idea how to prevent this? Maybe the character range is incorrect?



$letter = chr(64+rand(0,26));









share|improve this question



























    8















    I'm using the following to generate a random character from A-Z, but it's occasionally generating the @ symbol. Any idea how to prevent this? Maybe the character range is incorrect?



    $letter = chr(64+rand(0,26));









    share|improve this question

























      8












      8








      8


      2






      I'm using the following to generate a random character from A-Z, but it's occasionally generating the @ symbol. Any idea how to prevent this? Maybe the character range is incorrect?



      $letter = chr(64+rand(0,26));









      share|improve this question














      I'm using the following to generate a random character from A-Z, but it's occasionally generating the @ symbol. Any idea how to prevent this? Maybe the character range is incorrect?



      $letter = chr(64+rand(0,26));






      php






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 15 '15 at 21:03









      michellemichelle

      1751317




      1751317
























          4 Answers
          4






          active

          oldest

          votes


















          20














          Use this it's easier.



          Upper Case



          $letter = chr(rand(65,90));


          Lowercase



          $letter = chr(rand(97,122));


          ascii chart



          The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.



          function izrand($length = 32) {

          $random_string="";
          while(strlen($random_string)<$length && $length > 0) {
          $randnum = mt_rand(0,61);
          $random_string .= ($randnum < 10) ?
          chr($randnum+48) : ($randnum < 36 ?
          chr($randnum+55) : $randnum+61);
          }
          return $random_string;
          }



          update: 12/19/2015




          Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add
          the second paramater as true.




          Example Usage




          $randomNumber = izrand(32, true); // generates 32 digit number as string
          $randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string




          Typecast to Integer




          If you want to typecast the number to integer, simply do this after you
          generate the number. NOTE: This will drop any leading zeros if they exist.



          $randomNumber = (int) $randomNumber;




          izrand() v2




          function izrand($length = 32, $numeric = false) {

          $random_string = "";
          while(strlen($random_string)<$length && $length > 0) {
          if($numeric === false) {
          $randnum = mt_rand(0,61);
          $random_string .= ($randnum < 10) ?
          chr($randnum+48) : ($randnum < 36 ?
          chr($randnum+55) : chr($randnum+61));
          } else {
          $randnum = mt_rand(0,9);
          $random_string .= chr($randnum+48);
          }
          }
          return $random_string;
          }





          share|improve this answer





















          • 1





            You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

            – IncredibleHat
            Dec 4 '17 at 14:15













          • Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

            – Peter O.
            Nov 21 '18 at 7:23



















          3














          ASCII code 64 is @. You want to start at 65, which is A. Also, PHP's rand generates a number from min to max inclusive: you should set it to 25 so the biggest character you get is 90 (Z).



          $letter = chr(65 + rand(0, 25));





          share|improve this answer



















          • 2





            why not just `chr(rand(65,90));'?

            – Tony Chiboucas
            Nov 7 '17 at 23:10



















          1














          You could use, given you could generate from a-Z:



          $range = array_merge(range('A', 'Z'),range('a', 'z'));
          $index = array_rand($range, 1);
          echo $range[$index];





          share|improve this answer
























          • rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

            – Tony Chiboucas
            Nov 7 '17 at 23:12



















          0














          $range = range('A', 'Z');
          $index = array_rand($range);
          echo $range[$index];





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31441050%2fusing-chr-rand-to-generate-a-random-character-a-z%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            20














            Use this it's easier.



            Upper Case



            $letter = chr(rand(65,90));


            Lowercase



            $letter = chr(rand(97,122));


            ascii chart



            The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.



            function izrand($length = 32) {

            $random_string="";
            while(strlen($random_string)<$length && $length > 0) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : $randnum+61);
            }
            return $random_string;
            }



            update: 12/19/2015




            Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add
            the second paramater as true.




            Example Usage




            $randomNumber = izrand(32, true); // generates 32 digit number as string
            $randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string




            Typecast to Integer




            If you want to typecast the number to integer, simply do this after you
            generate the number. NOTE: This will drop any leading zeros if they exist.



            $randomNumber = (int) $randomNumber;




            izrand() v2




            function izrand($length = 32, $numeric = false) {

            $random_string = "";
            while(strlen($random_string)<$length && $length > 0) {
            if($numeric === false) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : chr($randnum+61));
            } else {
            $randnum = mt_rand(0,9);
            $random_string .= chr($randnum+48);
            }
            }
            return $random_string;
            }





            share|improve this answer





















            • 1





              You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

              – IncredibleHat
              Dec 4 '17 at 14:15













            • Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

              – Peter O.
              Nov 21 '18 at 7:23
















            20














            Use this it's easier.



            Upper Case



            $letter = chr(rand(65,90));


            Lowercase



            $letter = chr(rand(97,122));


            ascii chart



            The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.



            function izrand($length = 32) {

            $random_string="";
            while(strlen($random_string)<$length && $length > 0) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : $randnum+61);
            }
            return $random_string;
            }



            update: 12/19/2015




            Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add
            the second paramater as true.




            Example Usage




            $randomNumber = izrand(32, true); // generates 32 digit number as string
            $randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string




            Typecast to Integer




            If you want to typecast the number to integer, simply do this after you
            generate the number. NOTE: This will drop any leading zeros if they exist.



            $randomNumber = (int) $randomNumber;




            izrand() v2




            function izrand($length = 32, $numeric = false) {

            $random_string = "";
            while(strlen($random_string)<$length && $length > 0) {
            if($numeric === false) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : chr($randnum+61));
            } else {
            $randnum = mt_rand(0,9);
            $random_string .= chr($randnum+48);
            }
            }
            return $random_string;
            }





            share|improve this answer





















            • 1





              You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

              – IncredibleHat
              Dec 4 '17 at 14:15













            • Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

              – Peter O.
              Nov 21 '18 at 7:23














            20












            20








            20







            Use this it's easier.



            Upper Case



            $letter = chr(rand(65,90));


            Lowercase



            $letter = chr(rand(97,122));


            ascii chart



            The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.



            function izrand($length = 32) {

            $random_string="";
            while(strlen($random_string)<$length && $length > 0) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : $randnum+61);
            }
            return $random_string;
            }



            update: 12/19/2015




            Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add
            the second paramater as true.




            Example Usage




            $randomNumber = izrand(32, true); // generates 32 digit number as string
            $randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string




            Typecast to Integer




            If you want to typecast the number to integer, simply do this after you
            generate the number. NOTE: This will drop any leading zeros if they exist.



            $randomNumber = (int) $randomNumber;




            izrand() v2




            function izrand($length = 32, $numeric = false) {

            $random_string = "";
            while(strlen($random_string)<$length && $length > 0) {
            if($numeric === false) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : chr($randnum+61));
            } else {
            $randnum = mt_rand(0,9);
            $random_string .= chr($randnum+48);
            }
            }
            return $random_string;
            }





            share|improve this answer















            Use this it's easier.



            Upper Case



            $letter = chr(rand(65,90));


            Lowercase



            $letter = chr(rand(97,122));


            ascii chart



            The code below generates a random alpha-numeric string of $length. You can see the numbers there for what you need.



            function izrand($length = 32) {

            $random_string="";
            while(strlen($random_string)<$length && $length > 0) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : $randnum+61);
            }
            return $random_string;
            }



            update: 12/19/2015




            Here is an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add
            the second paramater as true.




            Example Usage




            $randomNumber = izrand(32, true); // generates 32 digit number as string
            $randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string




            Typecast to Integer




            If you want to typecast the number to integer, simply do this after you
            generate the number. NOTE: This will drop any leading zeros if they exist.



            $randomNumber = (int) $randomNumber;




            izrand() v2




            function izrand($length = 32, $numeric = false) {

            $random_string = "";
            while(strlen($random_string)<$length && $length > 0) {
            if($numeric === false) {
            $randnum = mt_rand(0,61);
            $random_string .= ($randnum < 10) ?
            chr($randnum+48) : ($randnum < 36 ?
            chr($randnum+55) : chr($randnum+61));
            } else {
            $randnum = mt_rand(0,9);
            $random_string .= chr($randnum+48);
            }
            }
            return $random_string;
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 21 '18 at 7:25









            Peter O.

            21k95969




            21k95969










            answered Jul 15 '15 at 21:32









            Tech SavantTech Savant

            2,79611037




            2,79611037








            • 1





              You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

              – IncredibleHat
              Dec 4 '17 at 14:15













            • Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

              – Peter O.
              Nov 21 '18 at 7:23














            • 1





              You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

              – IncredibleHat
              Dec 4 '17 at 14:15













            • Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

              – Peter O.
              Nov 21 '18 at 7:23








            1




            1





            You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

            – IncredibleHat
            Dec 4 '17 at 14:15







            You have an error in the last portion of the selector: ($randnum < 36 ? chr($randnum+55) : $randnum+61) ... should be ($randnum < 36 ? chr($randnum+55) : chr($randnum+61))...

            – IncredibleHat
            Dec 4 '17 at 14:15















            Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

            – Peter O.
            Nov 21 '18 at 7:23





            Since PHP 7, random_int (a cryptographic RNG) should be used rather than rand or mt_rand.

            – Peter O.
            Nov 21 '18 at 7:23













            3














            ASCII code 64 is @. You want to start at 65, which is A. Also, PHP's rand generates a number from min to max inclusive: you should set it to 25 so the biggest character you get is 90 (Z).



            $letter = chr(65 + rand(0, 25));





            share|improve this answer



















            • 2





              why not just `chr(rand(65,90));'?

              – Tony Chiboucas
              Nov 7 '17 at 23:10
















            3














            ASCII code 64 is @. You want to start at 65, which is A. Also, PHP's rand generates a number from min to max inclusive: you should set it to 25 so the biggest character you get is 90 (Z).



            $letter = chr(65 + rand(0, 25));





            share|improve this answer



















            • 2





              why not just `chr(rand(65,90));'?

              – Tony Chiboucas
              Nov 7 '17 at 23:10














            3












            3








            3







            ASCII code 64 is @. You want to start at 65, which is A. Also, PHP's rand generates a number from min to max inclusive: you should set it to 25 so the biggest character you get is 90 (Z).



            $letter = chr(65 + rand(0, 25));





            share|improve this answer













            ASCII code 64 is @. You want to start at 65, which is A. Also, PHP's rand generates a number from min to max inclusive: you should set it to 25 so the biggest character you get is 90 (Z).



            $letter = chr(65 + rand(0, 25));






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 15 '15 at 21:08









            franciscodfranciscod

            908317




            908317








            • 2





              why not just `chr(rand(65,90));'?

              – Tony Chiboucas
              Nov 7 '17 at 23:10














            • 2





              why not just `chr(rand(65,90));'?

              – Tony Chiboucas
              Nov 7 '17 at 23:10








            2




            2





            why not just `chr(rand(65,90));'?

            – Tony Chiboucas
            Nov 7 '17 at 23:10





            why not just `chr(rand(65,90));'?

            – Tony Chiboucas
            Nov 7 '17 at 23:10











            1














            You could use, given you could generate from a-Z:



            $range = array_merge(range('A', 'Z'),range('a', 'z'));
            $index = array_rand($range, 1);
            echo $range[$index];





            share|improve this answer
























            • rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

              – Tony Chiboucas
              Nov 7 '17 at 23:12
















            1














            You could use, given you could generate from a-Z:



            $range = array_merge(range('A', 'Z'),range('a', 'z'));
            $index = array_rand($range, 1);
            echo $range[$index];





            share|improve this answer
























            • rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

              – Tony Chiboucas
              Nov 7 '17 at 23:12














            1












            1








            1







            You could use, given you could generate from a-Z:



            $range = array_merge(range('A', 'Z'),range('a', 'z'));
            $index = array_rand($range, 1);
            echo $range[$index];





            share|improve this answer













            You could use, given you could generate from a-Z:



            $range = array_merge(range('A', 'Z'),range('a', 'z'));
            $index = array_rand($range, 1);
            echo $range[$index];






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 15 '15 at 21:09









            ka_linka_lin

            6,80042844




            6,80042844













            • rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

              – Tony Chiboucas
              Nov 7 '17 at 23:12



















            • rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

              – Tony Chiboucas
              Nov 7 '17 at 23:12

















            rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

            – Tony Chiboucas
            Nov 7 '17 at 23:12





            rather than range(), why not str_split()? echo array_rand(str_split('ABCDEFGHIJKLMNOP'),1);

            – Tony Chiboucas
            Nov 7 '17 at 23:12











            0














            $range = range('A', 'Z');
            $index = array_rand($range);
            echo $range[$index];





            share|improve this answer




























              0














              $range = range('A', 'Z');
              $index = array_rand($range);
              echo $range[$index];





              share|improve this answer


























                0












                0








                0







                $range = range('A', 'Z');
                $index = array_rand($range);
                echo $range[$index];





                share|improve this answer













                $range = range('A', 'Z');
                $index = array_rand($range);
                echo $range[$index];






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Oct 7 '17 at 12:30









                lukyluky

                612915




                612915






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31441050%2fusing-chr-rand-to-generate-a-random-character-a-z%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Guess what letter conforming each word

                    Port of Spain

                    Run scheduled task as local user group (not BUILTIN)