i have an array with many values and i want to get one value is many show of all values. Like this.
my array
$allValues = array(0,1,1); // i want to get 1, because two 1 vs one 0
// other example
$allValue = array(0,0,0,1,1); // I want to get 0, because three 0 vs two 1
// other example
$allValues = array(0,1); // I want to get 0, because one 0 vs one 1 is 50:50 but 0 is first value
Sorry for my bad english.
<?php
$allValues = array(0,1,1);
$result=array_count_values($allValues); // Count occurrences of everything
arsort($result); // Sort descending order
echo key($result); // Pick up the value with highest number
?>
Edit: I've used key() because you are interested in knowing the value which has most number of occurrences and not the number itself. If you just need the number you can remove key() call.
Fiddle
try this
$allValues = array(0,0,0,1,1);
$count = array_count_values($allValues);
echo $val = array_search(max($count), $count);
Works only with 0s and 1s
function evaluateArray($array) {
$zeros = 0;
$ones = 0;
foreach($array as $item) {
if($item == 0) {
$zeros++;
} else {
$ones++;
}
}
// Change this if you want to return 1 if the result is equal
// To return ($ones >= $zeros) ? 1 : 0;
return ($zeros >= $ones) ? 0 : 1;
}
Try this:
function find_value($array) {
$zeros = 0;
$ones = 0;
for($i = 0; $i < count($array); $i++) {
($array[$i] == 0) ? $zeros++ : $ones++;
}
if($zeros == $ones) return $array[0];
return ($zeros > $ones) ? 0 : 1;
}
you can use array_count_values β Counts all the values of an array
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
Related
I have the following array:
$array = [2,2,5,2,2];
I would like to get the number which is different from the others, for example all the numbers are 2 except the number 5. So Is there anyway to get the different number using any array method or better solution? My solution is:
$array = [2,2,5,2,2];
$array1 = [4,4,4,6,4,4,4];
$element = -1;
$n = -1;
$count = 0;
for($i=0; $i<count($array1); $i++) {
if($element !== $array1[$i] && $element !== -1 & $count==0) {
$n = $array1[$i];
$count++;
}
$element = $array1[$i];
}
dd($n);
You can use array_count_values for group and count same value like:
$array = [2,2,5,2,2];
$countarray = array_count_values($array);
arsort($countarray);
$result = array_keys($countarray)[1]; // 5
Since you only have two numbers, you will always have the number with the least equal values ββin second position
Reference:
array_count_values
array_keys
A small clarification, for safety it is better to use arsort to set the value in second position because if the smallest number is in first position it will appear as the first value in the array
Sorting Arrays
You can user array_count_values which returns array with item frequency.
Then use array_filter to filter out data as follow:
$arrayData = [2,2,2,5];
$filterData = array_filter(array_count_values($arrayData), function ($value) {
return $value == 1;
});
print_r($filterData);
Inside array_filter(), return $value == 1 means only get the data with 1 frequency and thus filter out the other data.
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
print $number . ' | ' . ($count > 1 ? 'Duplicate value ' : 'Unique value ') . "\n";
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
UniqueAndDuplicat($array1);
//output: 2 | duplicate value 5 | Unique value
UniqueAndDuplicat($array2);
//output: 4 | duplicate value 5 | Unique value
?>
Use this function to reuse this you just call this function and pass an Array to this function it will give both unique and duplicate numbers.
If you want to return only Unique number then use the below code:
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
if($count == 1){
return $number;
}
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
echo UniqueAndDuplicat($array1); // 5
echo "<br>";
echo UniqueAndDuplicat($array2); // 6
?>
I have an array [4,3,5,5,7,6] and I want to loop through the sorted one and subtract the highest value from the preceding value, then subtract the remainder from the value behind it and so on, then in the end, I need one final value that comes when the loop is completed.
For example
Above array will be sorted like
Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 5
[4] => 6
[5] => 7
)
Now I want to find the difference between arr[5] and arr[4], the result will be 1, then subtract the result from arr[3] and so on till the loop is completed
This is what I tried but it doesn't seem to work
for ($i = count($a)-1; $i >0; $i--){
echo $result = $a[$i] - $a[$i-1];
echo "<br />";
if($result > 0) {
if($result > $a[$i-2]) {
echo $result = $result - $a[$i-2];
} else {
}
}
I think there is a more simple and fast way to achieve this:
$array = [4, 3, 5, 5, 7, 6];
rsort($array);
$result = $array[0] - $array[1];
for($i = 2, $count = count($array); $i < $count; $i++){
$result = $array[$i] - $result;
}
print($result);
output:
0
Do you wish this way?
$a = [1,1,1,3,1,7];
$result = null;
for ($i = count($a)-1; $i >0; $i--){
if($result == null)
$result = $a[$i-1];
echo $result = $a[$i] - $result;
echo "<br />";
if($result == 0) break;
}
My first answer was wrong, i see you need to discard 2 keys after the first substraction.
This does the job:
<?php
$array = [3,4,5,5,6,7];
$reverse = array_reverse($array);
if (count($reverse) > 1) {
$first = $reverse[0] - $reverse[1];
} else {
//code should stop
}
$result = $first;
for ($i = 2; $i < count($reverse); $i++) {
$result = $reverse[$i] - $result;
}
echo $result;
Ouputs 0, just as in your example. And of course this code still needs check to see if the key of the array does exist while iterating
$numbers = [4,3,5,5,7,6];
sort($numbers);
$numbers = array_reverse($numbers);
$first = array_shift($numbers);
$second = array_shift($numbers);
$result = array_reduce($numbers, function ($carry, $current_item) {
return $current_item - $carry;
}, ($first - $second));
echo $result;
To get the expected output you are seeking you can use rsort to sort descending and start with the highest number. The first 2 elements are subtracted to get the starting value. Loop through the remainder to get your result.
Here's how you can achieve that:
$a = [4, 3, 5, 5, 7, 6]; // Your unsorted array
rsort($a); // Sort array by descending of largest to smallest
$result = $a[0] - $a[1]; // Initial subtraction of first two values
unset($a[0], $a[1]); // Remove from array so it won't loop through
foreach ($a as $_a) { // Loop through remainder and subtract difference
$result = $_a - $result;
}
echo $result; // Show your result
Yields:
0
If you care about reindexing due to the unset you can simply add an extra line after that:
$a = array_values($a); // Reindexes array starting at 0 if you desire
I have a loop from 1 to 4, and I have an array which contain 1,2, and 4, but misses the number 3. How do I put or replace the missing 3 into 0 as my only thought to solve my problem, or get all the same values and then compare both sides? Because I need to compare both sides if it's same or not.
With this code, I'm getting the error: "undefined offset 3".
$a = array(1,2,4);
for ($i=1; $i <= 4; $i++) {
if ($i==$a[$i]) {
echo 'true';
} else {
false;
}
}
Is there other way to compare all those that have same value like
1 & 1 = true
2 & 2 = true
3 & = false
4 & 4 = true
And display something like
1. true
2. true
3. false
4. true
Probably the most straightforward way is to use in_array().
$a = [1, 2, 4];
for ($i = 1; $i <= 4; $i++) {
echo $i.'. '.(in_array($i, $a) ? 'true' : 'false').PHP_EOL;
}
Here is a working example.
Something like that :
$a = array(1,2,4);
$flipped = array_flip($a);
for($i = 1; $i <= 4; $i++){
$res[$i]="false";
if(array_key_exists($i, $flipped)){
$res[$i] = "true";
}
}
foreach($res as $key=>$value){
echo $key.". ".$value."<br/>";
}
The values in your array: $a = array(1, 2, 4) will not correspond to the $i in your for loop when you use $a[$i], because the value inside the square brackets refers to the key of the array, not to the value.
An array in PHP is an ordered map, with keys corresponding to values. When you define an array of values without assigning keys, like $a = array(1, 2, 4), PHP automatically creates integer keys for each of the values, beginning with zero, so in effect you are creating this array:
[0 => 1, 1 => 2, 2 => 4]
With the code you showed, you should be getting an undefined offset notice for 4 as well as 3.
If your array is sorted, one way to check for missing elements in your sequence is to check the current value of the array for each increment of your for loop, and move to the next element when a value matches.
$a = array(1,2,4);
for ($i=1; $i <= 4; $i++) {
if (current($a) == $i){
echo "$i: true".PHP_EOL;
next($a);
} else {
echo "$i: false".PHP_EOL;
}
}
The array must be sorted for this to work. If it is not in order as it is in your example, you can sort it with sort($a);.
I am trying to write a function that will check if the array can be sorted with a single swap of the values in the array.
For example: array(1,3,5,3,7) must return true, but array(1,3,5,3,4) must return false.
I tried the following code below, but I'm stuck with it:
$noOfIterations = 0;
for($x = 0; $x < count($a)-2; $x++) {
if($a[$x] > $a[$x+1]) {
$noOfIterations ++;
}
}
return $noOfIterations >1;
// The below solution helped as well.
//$arr = [1, 3, 5, 3, 7]; //[1, 3, 5, 3, 4]
$arr = [1, 3, 5, 3, 4];
$sortedArr = $arr;
sort($sortedArr);
print_r(array_intersect_assoc($arr,$sortedArr));
This should work for you:
(Here I first make a copy of the original array to then sort() it. After this I loop through both arrays with array_map() and look how many position has changed. With array_filter() I sort the elements out where no position has changed. Then you can simply check if 2 or more position has changed and print either FALSE or TRUE)
<?php
$arr = [1, 3, 5, 3, 7]; //[1, 3, 5, 3, 4]
$sortedArr = $arr;
sort($sortedArr);
$filtered = array_filter(
array_map(function($v1, $v2){
return ($v1 == $v2 ?FALSE:TRUE);
}, $arr, $sortedArr)
);
var_dump(count($filtered) > 2 ? FALSE : TRUE);
?>
output:
TRUE //FALSE
Execute the sort, then compare the original array with the sorted array using array_intersect_assoc().... if the difference is more than two elements, then the answer is 'no'
If you really wanna do it with a loop, you can do it with a double loop comparing each value to one another. You need to get a little creative with the comparing. From what I see, your code succeeds on the first array but fails on the second. It fails on the second one because you are only checking 2 adjacent entries and 3 is always less than 4. Or you can keep track of the largest number and count how many numbers are less than that value past it. Also make sure to add to the count if you encounter another bigger value. Hope all this makes sense.
What if array is sorted and no swap is needed?
It might help if I knew Why.
Try this, it works for your two example arrays.
function swap($array){
$prev = 0;
$count = 0;
foreach($array as $val){
if($val < $prev){
$count++;
}
else{
$prev = $val;
}
}
if($count < 2){return(true);}else{return(false);}
}
My answer in php.
function oneSwap($A){
$count=count($A);
$swaps=0;
$curr_max = 0;
$res = false;
for($i = 0; $i <= $count; $i++) {
if(isset($A[$i+1])){
if(($A[$i] >= $A[$i + 1]) && $curr_max >= $A[$i+1]){
$swaps++;
}
if($A[$i] >= $A[$i +1]){
$curr_max = $A[$i];
}
}
}
if(($swaps == 1) || ($swaps == 0 && $curr_max ==0)){
$res = true;
echo $res;
}
}
oneSwap([3,1,2,8]);
oneSwap([1,2,3]);
oneSwap([1,5,3,3,7]);
oneSwap([3,2,1,8]);
oneSwap([2,1,1,2]);
Given the following array:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
And assuming $n = 2, what is the most efficient way to get a count of each value in the array within $n of each value?
For example, 6 has 3 other values within $n: 5,7,7.
Ultimately I'd like a corresponding array with simply the counts within $n, like so:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
Is a simple foreach loop the way to go? CodePad Link
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);
My last answer was written without fully groking the problem...
Try sorting the array, before processing it, and leverage that when you run through it. This has a better runtime complexity.
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
asort($arr);
$n = 2;
$cnt = count($arr);
$counts = array_pad(array(), $cnt, 0);
for ($x=0; $x<$cnt; $x++) {
$low = $x - 1;
$lower_range_bound = $arr[$x]-$n;
while($low >= 0 && ($arr[$low] >= $lower_range_bound)) {
$counts[$x]++;
$low--;
}
$high = $x + 1;
$upper_range_bound = $arr[$x]+$n;
while($high < $cnt && $arr[$high] <= $upper_range_bound) {
$counts[$x]++;
$high++;
}
}
print_r($arr);
print_r($counts);
Play with it here: http://codepad.org/JXlZNCxW