How can PHP developers ensure that the total width of columns remains consistent when using weighting for calculations?

When using weighting for calculations in PHP to determine the width of columns in a table or grid layout, developers can ensure that the total width remains consistent by calculating the percentage width of each column based on the total weight assigned to all columns. This way, even if the content within each column varies in size, the overall layout will maintain a consistent total width.

$weights = [1, 2, 1]; // Example weights for three columns
$totalWeight = array_sum($weights);
$columnWidths = [];

foreach ($weights as $weight) {
    $columnWidths[] = ($weight / $totalWeight) * 100 . '%';
}

// Output the column widths for use in HTML/CSS
echo implode(' ', $columnWidths);