示例:
-50 , 60 , -4 , 80 , 25, -34, 15
输出将是130 -50,80是最大的差异
但我需要在php
我试过echo max(rand(-100, 100));
但它不是我正在寻找的输出
我也试过了:
$myarray = array(
'this' => 2,
'that' => 14,
'them' => -5,
'other' => 200,
'nothing' => 42,
'somethingelse' => 1,
'you' => 10,
'me' => 30);
foreach ($myarray as $key => $value) {
if (!isset ($min) || $value < $min) { $min = $value; }
if (!isset ($max) || $value > $max) { $max = $value; }
}
$diff = $max - $min;
echo $diff;
任何建议?
答案 0 :(得分:2)
<?php
$array = array(-50 , 60 , -4 , 80 , 25, -34, 15);
$min = 0;
$max = 0;
foreach($array as $element) {
if ($element < $min) $min = $element;
if ($element > $max) $max = $element;
}
echo $max - $min;
答案 1 :(得分:2)
使用max()
的方法没有错,但是max()
期望数组作为其第一个参数,而rand()
只返回一个整数。
解决方案应该是:
$diff = max($myarray) - min($myarray);
答案 2 :(得分:0)
尝试这个
$myarray = array(
'this' => 2,
'that' => 14,
'them' => -5,
'other' => 200,
'nothing' => 42,
'somethingelse' => 1,
'you' => 10,
'me' => 30);
function bigDiff($arr){
if(count($arr)>0){
$max = max($arr);
$min = min($arr);
$diff = ($max)-($min);
return $diff;
}
return "Null input array provided";
}
echo bigDiff($myarray);
输出205
答案 3 :(得分:0)
这可能是另一种方式:
$arr = array(
'this' => 2,
'that' => 14,
'them' => -5,
'other' => 200,
'nothing' => 42,
'somethingelse' => 1,
'you' => 10,
'me' => 30
);
sort($arr);
$diff = $arr[count($arr) - 1] - $arr[0];
答案 4 :(得分:0)
你可以试试这个:
$array = array(-50 , 60 , -4 , 80 , 25, -34, 15);
$max = max($array); //80
$min = min($array); //-50
$difference = $max - $min; //130