Browsing Random

Doing Random Things in PHP

Suppose you want to display something randomly in a news feed, or pick random elements from an array, or anything random in general. Programming Languages are used to define the way how something must be done. Hence in a technical way, it can’t do things randomly on it’s own. Otherwise it would be an AI (Artificial Intelligence). Doing random things is not done at compiling, but in execution. In case of PHP, this doesn’t matter as it’s an interpreter.


Generating Random String in PHP

In PHP you can generate random number by using rand function, but there is no specific function to generate a random text or string. In this post I’m going to show the function that will generate a random string of length mentioned. Here is the function: function rand_string($length) { $str=""; $chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $size = strlen($chars); for($i = 0;$i < $length;$i++) { $str .= $chars[rand(0,$size-1)]; } return $str; } Usage To generate a random string use rand_string() function with the parameter of length of the to be generated string.





This blog was once on WordPress. Now a static site. See source code on



Currently working on projects.