# Irregular Polygon Centroid Points in PHP

#### by Francis 2012-10-12 12:43:12

Irregular Polygon Centroid Points in PHP

Easy to find the center of irregular polygon points.

<?php

\$polygon = array(10,10, 10,50, 75,10, 100,100); // Points for Polygons

print_r(centroid(\$polygon, 4)); // Print centroid Points

function centroid(\$polygon,\$n) // Find Centroid points using this function
{
\$a = area(\$polygon,\$n);
\$cx = 0;
\$cy = 0;
\$polygon=array_chunk(\$polygon,2);

for (\$i=0;\$i<\$n;\$i++)
{
\$cx += (\$polygon[\$i][0] + \$polygon[\$i+1][0]) * ( (\$polygon[\$i][0]*\$polygon[\$i+1][1]) - (\$polygon[\$i+1][0]*\$polygon[\$i][1]) );
\$cy += (\$polygon[\$i][1] + \$polygon[\$i+1][1]) * ( (\$polygon[\$i][0]*\$polygon[\$i+1][1]) - (\$polygon[\$i+1][0]*\$polygon[\$i][1]) );
}
return(array( (1/(6*\$a))*\$cx,(1/(6*\$a))*\$cy));
}

function area(\$polygon,\$n) // Area of Polygon, Its to use find the centroid
{
\$polygon=array_chunk(\$polygon,2);
\$area = 0;
for (\$i=0;\$i<\$n;\$i++)
{
\$j = (\$i + 1);
\$area += \$polygon[\$i][0] * \$polygon[\$j][1];
\$area -= \$polygon[\$i][1] * \$polygon[\$j][0];
}
\$area /= 2;
return(abs(\$area));
}

?>

1401
0
0