Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – How can I loop through an array to compare consecutive values including first and last values

The following array contains a list of coordinates that I’m using to draw a polygon with ImageMagick:

$points = [
    ['x' => 40, 'y' => 10],
    ['x' => 20, 'y' => 20],
    ['x' => 70, 'y' => 50],
    ['x' => 60, 'y' => 15],
];

What I want to do is loop through this array and calculate the mid-point of each line segment by comparing each consecutive pair of coordinates including the first and last set i.e. the check must wrap-around either at the start or end of the loop. Is there a way to do this programatically without a lot of kludgey code to count the number of elements in the array and if() tests to determine when the first or last element has been reached, etc.?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use modulus to wrap around to 0 at the end.

$midpoints = [];
$len = count($points);
foreach ($points as $i => $point1) {
    $point2 = $points[($i+1) % $len];
    $midpoints[] = get_midpoint($point1, $point2);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading