w3resource logo
php Programming Exercies

PHP Challenges: Find the single element appears once in an array where every element appears twice except for one

PHP Challenges - 1: Exercise-11 with Solution

Write a PHP program to find the single element appears once in an array where every element appears twice except for one.

Input : array(5, 3, 0, 3, 0, 5, 7, 7, 9)

Sample Solution :

PHP Code :

<?php
function single_number($arr)
{
  $result = 0;
  
       for($i=0; $i<sizeof($arr); $i++)
       {
          $result =  $result ^ $arr[$i];   
          
       }
    return $result;
}
$num = array(5, 3, 0, 3, 0, 5, 7, 7, 9);
print_r(single_number($num)."\n")
?>

Sample Output:

9

Flowchart:

PHP Flowchart: Find the single element in an array where every element appears three times except for one

PHP Code Editor:

<?php
function single_number($arr)
{
  $result = 0;
  
       for($i=0; $i<sizeof($arr); $i++)
       {
          $result =  $result ^ $arr[$i];   
          
       }
    return $result;
}
$num = array(5, 3, 0, 3, 0, 5, 7, 7, 9);
print_r(single_number($num)."\n")
?>

Improve this sample solution and post your code through Disqus