homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Getting the biggest and smallest value from an array

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

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?



 4:08 pm on Feb 13, 2013 (gmt 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


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

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

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

if ($key&1)

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


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

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


 3:46 am on Feb 24, 2013 (gmt 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";

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved