How to make random names

0

I want to make a random text in a text written by a php web, the theme is that the one I have created creates the same name in all texts, and I want it to be random, I do not know if I explain it. I have this:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

echo generateRandomString();

And I want the generateRamdomString (); be inside of this:

echo "<tr><td> $mensaje</td></tr>";

It would be ahead of "$ message"

    
asked by MatiPHP 03.06.2018 в 19:46
source

1 answer

0

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.
answered by 03.06.2018 / 22:53
source