$variable1 =" toto ";
$变量2 = " helmut ";
$variable3 = 2;
QUESTION:将这些变量按顺序排序(将单词转换为与其长度相等的数字)。(使用条件if-else(或任何其他条件))
这是我做的代码,它有点长,我觉得我用得太多了,但事情是->如果我使用"A", "B", "C"作为变量,但是如果我用变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量变量。我不能像老师说的那样改变它们。所以我的代码不能工作。
$variable1 = "toto"; // strlen($variable1) = 4
$variable2 = "helmut"; // strlen($variable2) = 6
$variable3 = 2;
if (strlen($variable1) <= strlen($variable2)) {
if($variable3 <= strlen($variable1) ) {
echo $variable3 . "<br>" . strlen($variable1) . "<br>" . strlen($variable2);
}
if(strlen($variable2) <= $variable3) {
echo strlen($variable1) . "<br>" . strlen($variable2) . "<br>" . $variable3;
}
else {
echo strlen($variable1) . "<br>" . $variable3 . "<br>" . strlen($variable2);
}
}
else {
if ($variable3 <= strlen($variable2) ) {
echo $variable3 . "<br>" . strlen($variable2) . "<br>" . strlen($variable1);
}
if ($variable3 <= strlen($variable1) {
echo strlen($variable2) . "<br>" . $variable3 . "<br>" . strlen($variable1);
}
else {
echo strlen($variable2) . "<br>" . strlen($variable1) . "<br>" . $variable3;
}
}
我希望这是你需要的。
$variable1 = 'todo';
$variable2 = 'tetete';
$variable3 = 2;
$variablesToSort = [$variable1, $variable2, $variable3];
usort($variablesToSort, 'sortByLenght');
foreach($variablesToSort as $sortedVariable) {
echo $sortedVariable . ' ';
}
function sortByLenght($firstWord, $secondWord) {
return strlen($firstWord) <=> strlen($secondWord);
}
使用if else更新答案
$variable1 = '1';
$variable2 = '2';
$variable3 = 3;
$isFirstLongerThanSecond = strlen($variable1) > strlen($variable2);
$isSecondLongerThanThird = strlen($variable2) > strlen($variable3);
$isFirstLongerThanThird = strlen($variable1) > strlen($variable3);
if ($isFirstLongerThanSecond) {
if ($isSecondLongerThanThird) {
echo "$variable3 $variable2 $variable1";
} elseif ($isFirstLongerThanThird) {
echo "$variable2 $variable3 $variable1";
} else {
echo "$variable2 $variable1 $variable3";
}
} else if ($isSecondLongerThanThird) {
if ($isFirstLongerThanThird) {
echo "$variable3 $variable1 $variable2";
} else {
echo "$variable1 $variable3 $variable2";
}
} else if ($isFirstLongerThanThird) {
echo "$variable3 $variable1 $variable2";
} else {
echo "$variable1 $variable2 $variable3";
}