w3resource logo


php exercises

PHP Challenges: Find the single number which occurs odd numbers and other numbers occur even number

PHP Challenges - 1: Exercise-25 with Solution

Write a PHP program to find the single number which occurs odd numbers and other numbers occur even number.

Input : 4, 5, 4, 5, 2, 2, 3, 3, 2, 4, 4
Output : 2

Explanation :

PHP: find the single number which occurs odd numbers and other numbers occur even number.

Sample Solution :-

PHP Code :

<?php
function odd_occurrence($arr)
{

    $result = 0;
     
    # Traverse the array
    foreach ($arr as &$value)
    {
        # Xor (exclusive or)
        # Bits that are set in $a or $b but not both are set.
        $result = $result ^ $value;
    }
    return $result;
}
$num1 = array(4, 5, 4, 5, 2, 2, 3, 3, 2, 4, 4);

print_r(odd_occurrence($num1)."\n");
?>

Output :

2 

Flowchart:

PHP Flowchart: Find the single number which occurs odd numbers and other numbers occur even number

PHP Code Editor:

<?php
function odd_occurrence($arr)
{

    $result = 0;
     
    # Traverse the array
    foreach ($arr as &$value)
    {
        # Xor (exclusive or)
        # Bits that are set in $a or $b but not both are set.
        $result = $result ^ $value;
    }
    return $result;
}
$num1 = array(4, 5, 4, 5, 2, 2, 3, 3, 2, 4, 4);

print_r(odd_occurrence($num1)."\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