How can PHP developers optimize their code by using arrays to store and increment option counters when processing survey data from MySQL databases?

When processing survey data from MySQL databases in PHP, developers can optimize their code by using arrays to store and increment option counters. This approach allows for efficient tracking of the number of responses for each survey option without the need for multiple database queries. By utilizing arrays, developers can easily iterate through the survey data, incrementing the corresponding option counter in the array as they go.

// Assume $surveyData is an array containing survey responses fetched from the MySQL database

$optionCounters = []; // Initialize an empty array to store option counters

foreach ($surveyData as $response) {
    $option = $response['survey_option']; // Assuming 'survey_option' is the column name for survey options in the database
    if (isset($optionCounters[$option])) {
        $optionCounters[$option]++; // Increment the option counter if it already exists
    } else {
        $optionCounters[$option] = 1; // Initialize the option counter if it doesn't exist
    }
}

// Now $optionCounters will contain the number of responses for each survey option