| Getting the biggest and smallest value from an array
|
adder

msg:4545283 | 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?
|
jatar_k

msg:4545347 | 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
|
adder

msg:4547633 | 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) { unset($myarray[$key]); } }
$minX = min($myarray); $maxX = max($myarray);
|
swa66

msg:4547714 | 2:07 am on Feb 22, 2013 (gmt 0) | Efficiency ... since you already walk through it: remember the lowest and highest yourself.
|
astupidname

msg:4548296 | 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"; |
|
|
|
|