﻿ PHP: Find majority element in an array - w3resource

# 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)

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 :

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");
?>
```
```

Sample Output:

```5
6
```

Flowchart:

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