In this tutorial we are going to tackle a rather basic problem. How to determine the distance between two points on an X,Y grid.

Our starting points for the purpose of this tutorial will be (1,-10) and (15,-20). For our code we will be setting these values into variables but you can also accept them from a form as well as pull them from a MySQL database depending on your project.

First we'll set our variables and give them a value:

<?php // first coordinate set (1,-10) $x1 = 1; $y1 = -10; // second coordinate set (15,-20) $x2 = 15; $y2 = -20;

The next step is to subtract the x coordinate of the first set from the second set. We also need to do the same for the y coordinates. Then both values need to be squared. This is easily accomplished using PHP's pow(x,y) function. X equals the value to be raised, y equals the power to raise it by. If you want to know the value of 10 to the 9th power it would like pow(10,9)

$x = ( pow($x2,2) - pow($x1,2)); $y = ( pow($y2,2) - pow($y1,2));

The last step is to add these two values and find the square root.

$distance = ( sqrt($x + $y) );

For our example the final answer is 22.891046284519. If you want to round this value to nearest full number you can use the round() function, which will round the number up

**or**down. If you want to round to a certain number of decimal places, you can specify that such as round(11,3)

round($distance) returns the value: 23

round($distance,2) returns the value: 22.89

Putting it all together our code looks like:

<?php // first coordinate set (1,-10) $x1 = 1; $y1 = -10; // second coordinate set (15,-20) $x2 = 15; $y2 = -20; $x = ( pow($x2,2) - pow($x1,2)); $y = ( pow($y2,2) - pow($y1,2)); $distance = ( sqrt($x + $y) ); // Round to nearest full number $roundtofull = round($distance); $roundto2places = round($distance,2); ?>

This tutorial is really basic in showing how to determine distance, but I do hope you found it useful.