Welcome to WebmasterWorld Guest from 54.146.246.4

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Getting the biggest and smallest value from an array

     

adder

12:04 pm on Feb 13, 2013 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hi guys,

I've got an array with X,Y coordinates. There will be variable number of coordinates depending on the object.

This is what the array looks like:

12, 34, 13, 42, 18, 43, 20, 36

The odd possition is always X and the even position is Y. In other words:
Xs are: 12, 13, 18, 20
Ys are: 34, 42, 43, 36

I'm looking for an output like this:

$Xmax = 20
$Xmin = 12
$Ymax = 43
$Ymin = 34

What would be the most sensible way of doing this?

jatar_k

4:08 pm on Feb 13, 2013 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member



you could quickly loop though the array and put them into 2 other arrays, one for x values and one for y values

then it's easy enough to sort [php.net] each array then just grab the first and last value of each

adder

8:57 pm on Feb 21, 2013 (gmt 0)

10+ Year Member Top Contributors Of The Month



@jatar_k, good idea, thank you. I ended up splitting it like this:


foreach($myarray as $key => $value)
{

if ($key&1)
{
unset($myarray[$key]);
}
}

$minX = min($myarray);
$maxX = max($myarray);

swa66

2:07 am on Feb 22, 2013 (gmt 0)

WebmasterWorld Senior Member swa66 is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Efficiency ... since you already walk through it: remember the lowest and highest yourself.

astupidname

3:46 am on Feb 24, 2013 (gmt 0)

5+ Year Member



Or, to present another way, without looping:
$a = array(12, 34, 7.68966, -34.876, -65.8, -54.214, 87, 2);
preg_match_all('/(-?\d+\.?\d*)@(-?\d+\.?\d*)/', implode('@', $a), $coords);
//$coords[1] will be array containing all 'x' coordinates
//$coords[2] will be array containing all 'y' coordinates
$xmin = min($coords[1]);
$xmax = max($coords[1]);
$ymin = min($coords[2]);
$ymax = max($coords[2]);

echo "xmin = $xmin<br>xmax = $xmax<br>ymin = $ymin<br>ymax = $ymax";