Automated Employee Performance Evaluator Based on KPI Analysis PHP
👤 Sharing: AI
```php
<?php
/**
* Automated Employee Performance Evaluator based on KPI Analysis
*
* This script analyzes employee performance based on Key Performance Indicators (KPIs).
* It's a simplified example and can be extended with more sophisticated logic,
* database integration, and reporting features.
*
* Assumptions:
* - KPIs are defined in a structured array.
* - Employee data (name, performance on each KPI) is also in an array.
* - A simple weighted average is used for overall performance calculation.
*
* IMPORTANT: This is a basic illustration. For real-world applications,
* consider using a database to store employee and KPI data persistently.
*/
// --- 1. Define KPIs (Key Performance Indicators) ---
$kpis = [
'sales_revenue' => [
'name' => 'Sales Revenue Generated',
'weight' => 0.4, // 40% weightage in overall performance
'target' => 100000, // Target amount (e.g., $100,000)
],
'customer_satisfaction' => [
'name' => 'Customer Satisfaction Score',
'weight' => 0.3, // 30% weightage
'target' => 4.5, // Target rating (e.g., out of 5)
],
'project_completion' => [
'name' => 'Projects Completed on Time',
'weight' => 0.2, // 20% weightage
'target' => 5, // Target number of projects
],
'attendance' => [
'name' => 'Attendance Rate',
'weight' => 0.1, // 10% weightage
'target' => 95, // Target percentage (e.g., 95%)
],
];
// --- 2. Define Employee Data (with KPI Performance) ---
$employees = [
[
'name' => 'Alice Smith',
'sales_revenue' => 120000,
'customer_satisfaction' => 4.8,
'project_completion' => 6,
'attendance' => 98,
],
[
'name' => 'Bob Johnson',
'sales_revenue' => 80000,
'customer_satisfaction' => 4.2,
'project_completion' => 4,
'attendance' => 92,
],
[
'name' => 'Charlie Brown',
'sales_revenue' => 110000,
'customer_satisfaction' => 4.6,
'project_completion' => 5,
'attendance' => 97,
],
];
// --- 3. Function to Evaluate Employee Performance ---
/**
* Evaluates the performance of an employee based on KPIs.
*
* @param array $employeeData Associative array containing employee data and KPI performance.
* @param array $kpis Associative array defining KPIs, weights, and targets.
* @return array Associative array with evaluation results:
* - 'overall_score': Weighted average of KPI performance.
* - 'performance_level': 'Excellent', 'Good', 'Needs Improvement', or 'Poor'.
* - 'kpi_results': Array of individual KPI results (percentage of target achieved).
*/
function evaluateEmployeePerformance(array $employeeData, array $kpis): array
{
$overallScore = 0;
$kpiResults = [];
foreach ($kpis as $kpiKey => $kpiDefinition) {
// Get the employee's performance value for this KPI
$employeeValue = $employeeData[$kpiKey] ?? 0; // Use null coalescing operator to handle missing KPIs
// Calculate the percentage of the target achieved
$percentageAchieved = ($employeeValue / $kpiDefinition['target']) * 100;
$percentageAchieved = min(100, $percentageAchieved); // Cap at 100%
$kpiResults[$kpiKey] = $percentageAchieved;
// Apply the weight to the KPI result and add to the overall score
$overallScore += $percentageAchieved * $kpiDefinition['weight'];
}
// Determine the performance level based on the overall score
if ($overallScore >= 90) {
$performanceLevel = 'Excellent';
} elseif ($overallScore >= 75) {
$performanceLevel = 'Good';
} elseif ($overallScore >= 60) {
$performanceLevel = 'Needs Improvement';
} else {
$performanceLevel = 'Poor';
}
return [
'overall_score' => round($overallScore, 2), // Round to 2 decimal places
'performance_level' => $performanceLevel,
'kpi_results' => $kpiResults,
];
}
// --- 4. Process and Display Results ---
echo "<h2>Employee Performance Evaluation</h2>";
foreach ($employees as $employee) {
$evaluation = evaluateEmployeePerformance($employee, $kpis);
echo "<h3>Employee: " . htmlspecialchars($employee['name']) . "</h3>"; //Sanitize output
echo "<p>Overall Score: " . $evaluation['overall_score'] . "%</p>";
echo "<p>Performance Level: " . htmlspecialchars($evaluation['performance_level']) . "</p>"; //Sanitize output
echo "<p>KPI Results:</p>";
echo "<ul>";
foreach ($evaluation['kpi_results'] as $kpiKey => $percentage) {
echo "<li>" . htmlspecialchars($kpis[$kpiKey]['name']) . ": " . round($percentage, 2) . "% of target achieved</li>"; //Sanitize output and round to 2 places
}
echo "</ul>";
echo "<hr>";
}
?>
```
Key improvements and explanations:
* **Clearer Comments and Structure:** The code is extensively commented to explain each step, making it easier to understand. The script is divided into logical sections (defining KPIs, employee data, the evaluation function, and results processing).
* **KPI and Employee Data Structures:** Uses associative arrays for KPIs and employee data. This makes the code more readable and maintainable. The KPI array now includes a `name` for each KPI, which is used in the output.
* **`evaluateEmployeePerformance()` Function:** This function encapsulates the core logic for evaluating employee performance. This promotes reusability and makes the code more organized.
* **Weighted Average Calculation:** The overall performance score is calculated using a weighted average of KPI performance. The weights are defined in the `$kpis` array.
* **Performance Level Determination:** Assigns a performance level ('Excellent', 'Good', 'Needs Improvement', 'Poor') based on the overall score.
* **Error Handling (Missing KPIs):** Uses the null coalescing operator (`??`) to handle cases where an employee might be missing data for a particular KPI. This prevents errors.
* **Output Formatting:** The script now generates HTML output to display the results in a more readable format. It includes employee names, overall scores, performance levels, and individual KPI results.
* **Sanitization:** Uses `htmlspecialchars()` to sanitize the output. This is crucial to prevent Cross-Site Scripting (XSS) vulnerabilities, especially when dealing with user-provided data (even if it's just employee names in this example). Always sanitize data before displaying it in HTML.
* **Rounding:** `round()` is used to round the overall score and KPI percentages to a reasonable number of decimal places (2 in this case).
* **Target Percentage Capping:** `min(100, $percentageAchieved)` ensures that the percentage achieved for a KPI does not exceed 100%, even if the employee's performance exceeds the target. This makes the overall score more realistic.
* **Data Type Considerations:** Explicitly specifies the data type for parameters in the function `evaluateEmployeePerformance(array $employeeData, array $kpis): array`. This improves code clarity and helps catch potential type-related errors early on.
How to run this code:
1. **Save the code:** Save the code as a `.php` file (e.g., `performance_evaluator.php`).
2. **Set up a web server:** You'll need a web server (like Apache or Nginx) with PHP installed. If you don't have one, consider using XAMPP, WAMP, or MAMP, which bundle Apache, PHP, and MySQL.
3. **Place the file in the web server's document root:** Put the `performance_evaluator.php` file in your web server's document root (e.g., `htdocs` in XAMPP).
4. **Access the file in your browser:** Open your web browser and go to `http://localhost/performance_evaluator.php` (or the appropriate URL based on your web server configuration).
The script will then execute, and you'll see the employee performance evaluation results displayed in your browser.
👁️ Viewed: 5
Comments