In PHP, how can the importance of different fields in a profile be weighted for a more accurate percentage calculation?

When calculating the percentage completion of a user's profile, you can weight different fields by assigning each field a specific importance level. This can be done by assigning a weight value to each field based on its importance, and then calculating the total weighted sum of completed fields to get a more accurate percentage.

// Define weight values for each field
$weights = [
    'name' => 1,
    'email' => 2,
    'phone' => 3,
    'address' => 2
];

// Calculate total weighted sum of completed fields
$totalWeightedSum = 0;
foreach ($weights as $field => $weight) {
    if (!empty($userProfile[$field])) {
        $totalWeightedSum += $weight;
    }
}

// Calculate total possible weighted sum
$totalPossibleWeightedSum = array_sum($weights);

// Calculate percentage completion
$percentageCompletion = ($totalWeightedSum / $totalPossibleWeightedSum) * 100;