是否可以计算同一个数组php中两个值之间的差异?

时间:2016-01-28 21:51:34

标签: php arrays

我不知道是否可能。我有一个数组('2','4','9','16'),我想得到(2-4),(4-9)和(9-16)的值。每一个减去下一个数字,你有没有办法实现这一目标?感谢。

3 个答案:

答案 0 :(得分:1)

<?php
$array=array('2','4','9','16');

foreach( $array as $k=> $v){
 if($v !=end($array)){
   echo $v-$array[$k+1]."\n";
 }
}

更新为排除16-0

答案 1 :(得分:0)

当然是。例如。像这样:

$array = array(2, 4, 9, 16);

$output = array();

foreach ($array as $key => $number) {
    if (isset($array[$key+1])) {
        $output[$number] = $number - $array[$key+1];
    }
}

var_dump($output);

$output数组如下所示:

array(3) {
  [2]=>
  int(-2)
  [4]=>
  int(-5)
  [9]=>
  int(-7)
}

请注意,最后一个号码没有条目,因为您可以自然地不减去该号码的下一个号码,因为没有。

答案 2 :(得分:0)

记录的另一种方法:

$test_array = array(1,5,12,24,79);
$new_array = array();

$array_length = sizeof($test_array);

for($n = 1; $n <= ($array_length - 1); $n++)
{
    // Get the current value
    $x = current($test_array);

    // Move the internal pointer
    next($test_array);

    // Get the next value
    $y = current($test_array);

    // Calculate the result in the new array
    $new_array[] = $x-$y;
}
相关问题