Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to find the element with minimum occurrences in an array with PHP

1 Answer

0 votes
declare(strict_types=1);

/**
 * Finds the element with the minimum occurrences in an array.
 *
 * @param array<int|string> $array Input array containing int or string scalar values.
 * @return int|string|null The least frequent element, or null if the array is empty.
 */
function findMinOccurrence(array $array): int|string|null
{
    if (empty($array)) {
        return null;
    }

    // 1. Tally element frequencies (O(N) time complexity)
    $counts = array_count_values($array);

    // 2. Sort associative array by value ascending while maintaining key associations
    asort($counts);

    // 3. Extract the key of the first element (the one with the lowest count)
    return array_key_first($counts);
}

// Example usage:
$arr = [1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3];

$result = findMinOccurrence($arr);

if ($result !== null) {
    echo $result . PHP_EOL; // Output: 5
} else {
    echo "The array was empty." . PHP_EOL;
}



/*
run:

5

*/

 



answered Sep 25 by avibootz
...