i have an array that contains numbers.

i want to work out the greatest differnce between any 2 values.
ie

$breaks [2] = '2';
$breaks [5] = '5';
$breaks [7] = '7';
$breaks [9] = '9';
$breaks [15] = '15';
$breaks [20] = '20';
$breaks [22] = '22';

// greatest difference here is 6

the purpose is that a table is being drawn, and counting each cell, line breaks occur when $count equals an amount in the array.

i need to workout the widest the table is going to be for formatting and colspan uses.

is there a function i can use to do this or am i going to start from the bottom comparing each value with each other?

    Looks like PHP does not have an adjacent difference function, so you will have to write one yourself.

      any visible problems here??.....

      <?php
      $arr1 = array(2,6,77,44,55,7,88,3,22,7);
      $c=0;
      
      foreach($arr1 as $v)
      {
      
      while($c < count($arr1))
      	{
      	$diff[] = $arr1[$c] - $v;
      	$c++;
      	}
      
      $c=0;
      }
      
      echo max($diff);
      ?>
      

        any visible problems here??.....

        Yes. Your original example is about finding the largest difference between any two adjacent elements. The new code you posted is about finding the largest difference between any two elements.

        If you want to find the largest adjacent difference between two elements, then you could try:

        function maxAdjacentDifference($array)
        {
            $temp = $array;
            array_pop($array);
            array_shift($temp);
            return max(array_map(create_function('$a,$b', 'return $b-$a;'), $array, $temp));
        }

        If you really want to find the largest difference between any two elements, then you only need a one-liner:

        function maxDifference($array)
        {
            return max($array) - min($array);
        }

          thank you laserlight off to disect/work out how your code works,

          {head bowed, tail between legs}

            Write a Reply...