w3resource logo


php exercises

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)
Output : 9

Explanation :

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

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

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



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