I've got many answer about this question using other language but i want an answer in php language. Any one help me please This is my array look like
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];
I've got many answer about this question using other language but i want an answer in php language. Any one help me please This is my array look like
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];
Use array_count_values() like below:-
<?php
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];
$array_count_values = array_count_values($array);// get how many times a value appreas inside array
foreach($array_count_values as $key=>$val){ // now iterate over this newly created array
if($val ==1){ // if count is 1
echo $key. " in array come only one time.\n"; // this means value appears only one time inside array
}
}
Output:- https://eval.in/867433 OR https://eval.in/867434
If you want values in an array:-
<?php
$array = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11,13]; // increased one value to show you the output
$array_count_values = array_count_values($array);
$single_time_comming_values_array = [];
foreach($array_count_values as $key=>$val){
if($val ==1){
$single_time_comming_values_array[] = $key;
}
}
print_r($single_time_comming_values_array);
Output:- https://eval.in/867515
Here, you can use something like this-
<?php
function appearedOnce($arr)
{
$result = 0;
for($i=0; $i<sizeof($arr); $i++)
{
$result = $result ^ $arr[$i];
}
return $result;
}
$num = array(1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11);
print_r(appearedOnce($num)."\n")
?>
My initial response was to take a more pedestrian approach which works as you may note from this example. Then I chanced upon a related discussion.
Another approach involves sorting the array and then inspecting pairs of numbers for duplicates. The following code is a result of coupling the OP's array with my translation of the presumably C source code of Michael Martin into PHP, as follows:
<?php
$arr = [1, 2, 3, 4, 4, 1, 2, 5, 5, 11, 11];
sort($arr);
for($i = 0, $max = count($arr); $i < $max; $i++){
// is single number last element in array?
if($i == count($arr)-1)
$singleNum = $arr[$i];
// If adjacent elements the same, skip
if($i < count($arr)-1 && $arr[$i] == $arr[$i+1]){
$i++;
}
else
{
// found single number.
$singleNum = $arr[$i];
}
}
var_dump($singleNum);
See live code