Welcome to WebmasterWorld Guest from 54.162.164.247

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)

#### Preferred Member from GB

joined:July 25, 2005
posts: 400
votes: 12

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)

#### Administrator

joined:July 24, 2001
posts:15756
votes: 0

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)

#### Preferred Member from GB

joined:July 25, 2005
posts: 400
votes: 12

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

#### Senior Member

joined:Aug 7, 2003
posts:4783
votes: 0

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

#### astupidname

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

#### Preferred Member

joined:Aug 18, 2008
posts:408
votes: 0

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";