PHP:检查两个随机单词是否不相同


PHP: Check if two random words are not the same

我正在开发一个昵称生成器工具。我有两个.json文件,其中包含第一个和第二个音节的数组。

第一个音节=单词的开头。

第二个音节=词尾。

以下是该工具如何生成一个随机昵称:

$name = ucwords($first_syllable[rand(0, count($first_syllable) - 1)] . $second_syllable[rand(0, count($second_syllable) - 1)]);

这很好,但现在我需要检查第一个音节和第二个音节是否不同。

例如,我在数组中有第一个音节"Dal",还有第二个音节"Dal"。我不希望该工具生成"达尔"。这就是为什么,我需要检查第一个音节是否与第二个音节不同。

非常感谢您的帮助。

只需检查它们是否相同-

$name1 = $first_syllable[rand(0, count($first_syllable) - 1)]; 
$name2 = $second_syllable[rand(0, count($second_syllable) - 1)];
if (strtolower($name1) !== strtolower($name2)) {
    $name = ucwords($name1 . $name2);
}
$firstS = ucwords($first_syllable[rand(0, count($first_syllable) - 1)]);
$secondS = ucwords($second_syllable[rand(0, count($second_syllable) - 1)]);
if($firstS != $secondS)
  $name = $firstS.$secondS;

最简单的解决方案是将选定的值存储在变量中,然后循环直到它们不同。

循环将确保您的两个值不同。

代码示例(未测试):

<?php
$second_syllable_value = '';
$first_syllable_value = '';
while ($second_syllable_value == $first_syllable_value)
{
    $first_syllable_value = $second_syllable[rand(0, count($second_syllable) - 1)];
    $second_syllable_value = $second_syllable[rand(0, count($second_syllable) - 1)];
}
?>

请小心数组的长度,因为您最终可能会陷入无限循环。