w3resource logo


php exercises

PHP Challenges: Find majority element in an array

PHP Challenges - 1: Exercise-23 with Solution

Write a PHP program to find majority element in an array.

Input : array(1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6)
Output : 5

Note: The majority element is the element that appears more than n/2 times where n is the number of elements in the array.

Explanation :

PHP: Find majority element in an array

Sample Solution :-

PHP Code :

<?php
function majority_element($arr)
 {
        $idx = 0;
        $ctr = 1;
        
        for($i=1; $i<sizeof($arr); $i++)
        {
            if ($arr[$idx] == $arr[$i])
            {
                $ctr += 1;
            }
            else
             {
                $ctr -= 1;
                if ($ctr == 0)
                {
                    $idx = $i;
                    $ctr = 1;
                }
          }   
        }      
    return $arr[$idx];
}
$num1 = array(1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6);
$num2 = array(1,2,3,3,3,3,2,3,5,3,1,3,3,4,6,1,3,3,4,6,6);
print_r(majority_element($num1)."\n");
print_r(majority_element($num2)."\n");
?>

Output :

5                                                           
6

Flowchart:

PHP Flowchart: Find majority element in an array

PHP Code Editor:

<?php
function majority_element($arr)
 {
        $idx = 0;
        $ctr = 1;
        
        for($i=1; $i<sizeof($arr); $i++)
        {
            if ($arr[$idx] == $arr[$i])
            {
                $ctr += 1;
            }
            else
             {
                $ctr -= 1;
                if ($ctr == 0)
                {
                    $idx = $i;
                    $ctr = 1;
                }
          }   
        }      
    return $arr[$idx];
}
$num1 = array(1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6);
$num2 = array(1,2,3,3,3,3,2,3,5,3,1,3,3,4,6,1,3,3,4,6,6);
print_r(majority_element($num1)."\n");
print_r(majority_element($num2)."\n");
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number