PHP:获取变量

时间:2017-01-22 11:56:49

标签: php

他们以任何方式获得变量中的最高和最低值吗?

示例是我有这个变量

$val1 = 10
 $val2 = 20
 $val3 = 30
 $val4 = 40
 $val5 = 50

在这个变量中,我希望显示或将具有最高和最低值的变量放到另一个变量中。就像下面一样。

$highval = $val5; 
$lowval = $val1;
$val5中的

$highval因为它的值为50 和 $val1中的$lowval因为它的值为10。

感谢

3 个答案:

答案 0 :(得分:2)

我的建议是将得分放在一个数组中,如下所示:

$scores = array(1, 2, 4, 5);
$highest = max($scores);
$lowest = min($scores);

答案 1 :(得分:1)

当您比较值列表时,最好将它们存储在数组中。

试试这个:

$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

答案 2 :(得分:0)

好吧,也许你已经找到了解决方案......

变量不得包含类似于示例的数字

$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)