如何让这个 PHP 函数生成两个随机字符串而不是一个?

How to make this PHP function generate two random string instead of one?

我想知道是否有办法让下面的 PHP 函数生成两个不同的字符串而不是一个?

function random_uuid( $length = 25 ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $uuid = substr( str_shuffle( $chars ), 0, $length );
    return $uuid;
}

$uuid = random_uuid(25);
<?php
function random_uuid( $length = 25 ) {
$array=array();
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$uuid1 = substr( str_shuffle( $chars ), 0, $length );
    array_push($array,$uuid1);
$uuid2 = substr( str_shuffle( $chars ), 0, $length );
    array_push($array,$uuid2);
return $array;
}
$stuff = random_uuid();
var_dump($stuff);

也许吧?

在 PHP 中,好的做法是函数完全按预期执行。所以你已经有了一个功能:

function random_uuid( $length = 25 ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $uuid = substr( str_shuffle( $chars ), 0, $length );
    return $uuid;
}

它完美地完成了它的工作——生成随机 uuid。现在你可以创建另一个函数,它将调用这个函数两次:

function generate_two_strings($length) {
    return array(
        random_uuid($length),
        random_uuid($length)
    );
}

$result = generate_two_strings(15);

print_r($result);

最佳实践

  • 函数完成它唯一的工作
  • 您拆分代码并保持函数小