他们有没有办法在变量中得到最高和最低的值?
例如,我有这个变量
$val1 = 10
$val2 = 20
$val3 = 30
$val4 = 40
$val5 = 50在这个变量中,我想显示或赋值给另一个变量,这个变量的值最高,也最低。就像下面这样。
$highval = $val5;
$lowval = $val1;$val5表示为$highval,因为它的值为50,$val1表示为$lowval,因为它的值为10。
谢谢
发布于 2017-01-22 20:01:19
当您比较一个值列表时,最好将它们存储在数组中。
试试这个:
$val1 = 10;
$val2 = 20;
$val3 = 30;
$val4 = 40;
$val5 = 50;
$arr = compact('val1','val2','val3','val4','val5'); // Stores values in array $arr
$highval = max($arr); // 50
$lowval = min($arr); // 10发布于 2017-01-22 20:00:25
我的建议是将分数放在一个数组中,如下所示:
$scores = array(1, 2, 4, 5);
$highest = max($scores);
$lowest = min($scores);发布于 2017-06-18 05:57:50
也许你已经找到解决方案了..。
变量不能像您的示例那样包含数字
$val1 = 10;
$val2 = 20;
$val3 = 30;
$val4 = 40;
$val5 = 50;
$arr = compact('val1 ', 'val2 ', 'val3 ', 'val4 ', 'val5 ');
$highval = max($arr);
$lowval = min($arr);echo "$lowval"; // give val1 the first variable value In brackets inside
echo "$highval"; // give val5 the last variable value In brackets inside
lowval is val1 (10)
highval is val5 (50)
The above example will give correct results
(you got the right results because it happened
to have the values in ascending order).
WHY IS THIS WRONG !!!
see below
请注意,如果数据来自数据库或xml文件,则值是动态的,而不是递增的,在这种情况下,我们将返回错误的结果。
$val1 = 20;
$val2 = 30;
$val3 = 10;
$val4 = 50;
$val5 = 40;
$arr = compact('val1 ', 'val2 ', 'val3 ', 'val4 ', 'val5 ');
$highval = max($arr);
$lowval = min($arr); echo"$lowval"; // val1 give the first variable value In brackets inside
echo"$highval"; // val5 give the last variable value In brackets inside
The above example will give wrong results
lowval is val1 (20)
highval isval5 (40)
The right results are
lowval=val3 (10)
highval=val4 (50)
一个简单的解决方案是用字母代替数字
$val1 = 30;
$val2 = 10;
$val3 = 50;
$val4 = 40;
$val5 = 20;
$vala = "$val1";
$valb = "$val2";
$valc = "$val3";
$vald = "$val4";
$vale = "$val5";
$arr = compact('vala ', 'valb ', 'valc ', 'vald ', 'vale ');
$highval = max($arr);
$lowval = min($arr);现在结果是正确的
echo "$lowval"; // give valb the lower value
echo "$highval"; // give valc the higher value
Now the results is correct
lowval is valb (10)
highval is valc (50)
https://stackoverflow.com/questions/41790581
复制相似问题