Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Program to Find the Number Occurring Odd Number of Times
Finding a number that occurs an odd number of times in an array is a common programming problem. In PHP, this can be solved using different approaches like counting, hashing, or bitwise XOR operations.
Problem Explanation
Given an array where all numbers appear an even number of times except one, we need to find that single number which appears an odd number of times.
For example, in the array [2, 3, 4, 3, 1, 4, 2, 1, 1], the number 1 appears 3 times (odd), while all other numbers appear an even number of times.
Method 1 Using Array Counting
This approach counts occurrences of each number and finds the one with odd count ?
<?php
function findOddNumber($arr) {
$count = array();
foreach($arr as $num) {
if(isset($count[$num])) {
$count[$num]++;
} else {
$count[$num] = 1;
}
}
foreach($count as $num => $occurrences) {
if($occurrences % 2 != 0) {
return $num;
}
}
return -1;
}
$arr = array(5, 7, 2, 7, 5, 2, 1, 1, 9, 9, 9);
$oddNumber = findOddNumber($arr);
if($oddNumber != -1) {
echo "The number occurring an odd number of times is: " . $oddNumber;
} else {
echo "No number occurs an odd number of times in the array.";
}
?>
The number occurring an odd number of times is: 9
Method 2 Using Bitwise XOR
The most efficient approach uses XOR operation. Since XOR of two identical numbers is 0, all even occurrences cancel out ?
<?php
function findOddUsingXOR($arr) {
$result = 0;
foreach ($arr as $value) {
$result = $result ^ $value;
}
return $result;
}
$arr = array(3, 5, 6, 2, 3, 6, 2, 5, 7);
$oddNumber = findOddUsingXOR($arr);
echo "The number occurring an odd number of times is: " . $oddNumber;
?>
The number occurring an odd number of times is: 7
Comparison
| Method | Time Complexity | Space Complexity |
|---|---|---|
| Array Counting | O(n) | O(n) |
| Bitwise XOR | O(n) | O(1) |
Conclusion
The XOR method is the most efficient solution with constant space complexity. Use array counting when you need to track all occurrences or handle multiple oddoccurring numbers.
