As has already been said in comments, you can use the following function, (originally proposed in this SO response in English ) to generate a 10-character random string:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
If you want more or less characters you can pass the amount you want when calling the function.
For your other questions, I would recommend that you use a string to which you add the data and then print it at the end.
For example:
$mensaje=": es el random generado";
$strHTML="<tr><td><b>".generateRandomString()."</b>$mensaje</td></tr>";
echo $strHTML;
This form is particularly useful especially when:
- in the code there are parts HTML / PHP ... in those cases many programmers write mixed code in which it is passed from PHP to HTML and vice versa, which is lawful, but results in a code that harms the seen and very difficult to analyze, debug, maintain.
- in the code there is content that will be built in different parts, such as conditions
if
, bulces for
or while
, etc. In those cases you could open your variable $strHTML
at the beginning of the code and go concatenating content during the entire route of the code to print it at the end.