I am still beginner.
I want to subtract a value in an array, then I want to compare values. I have an array, the values are not known, depend on the result of a function.
Example :
$value = [5,8,13,15];
I want to subtract each value and save it in an array. Example :
8-5 = 3
13-8 = 5
15-13 = 2
then I want to compare each value (3, 5, 2), which one is bigger.
Please help me. Thank you before.
$value = [5,18,13,15];
sort($value); //to not get negative results
$loop = 0;
$results = array();
while ($loop < count($value))
{
if ($loop == 0)
{
$loop++;
}
else
{
$firstval = $value[$loop];
$secondval = $value[$loop-1];
$results[] = intval($firstval) - intval($secondval);
$loop++;
}
}
sort($results);
$thebiggestkey = $results[count($results)-1];
This should do it for you
A small example with Indexes and Array, if you here is wishes it you can use Foreach to subtract all that there is in the Array
( http://php.net/manual/en/control-structures.foreach.php )
$value = [5,8,3,13,15];
$rep = $value[0] - $value[1];
//5 - 8
echo $rep;
//return -3
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
?>
Hi,
i have a problem to solve. i tired but not get the result good result
please ignore if i make a mistake in question.
Here is problem
My Approch
$nwe = ["5","2","C","D","+"];
$test = 0;
$last =[];
for ($i = 0; $i < sizeof($nwe); $i++) {
$last[] .= $nwe[$i];
$end = end($last);
if($end === "C"){
$t = prev($last);
$b = array_reverse(array_keys($nwe,$t));
if (( array_search($end, $nwe)) !== false) {
unset($nwe[$b[0]]);
array_pop($nwe);
}
}
if($end === "+"){
$test += prev($last);
$test += prev($last);
$nwe[$i] = $test;
}
if($end === "D"){
$t = 2;
$t *= prev($last);
$nwe[$i] = $t;
}
}
echo "<pre>";
print_r($last);
print_r($test);
print_r(array_sum($nwe));
echo "</pre>";
My Result
Help me to out from this.
It looks like some test to see how good you know your PHP functions. You need a few to solve this the easy way:
is_numeric() and (int) for the numbers. (link and link)
array_pop() to remove the last array entry. (link)
array_slice() to retrieve the last two elements of the array. (link)
array_sum() to get the total of all array numbers. (link)
end() to get the last value of an array. (link)
This is the above applied:
$nwe = ["5","-2","4","C","D","9","+","+","-"];
$result=[];
//LOOP the array
foreach($nwe as $v){
// IS IT A NUMBER ? (add number)
if(is_numeric($v)){
// just shove the number in $result
$result[]=(int)$v;
continue;
}
//IS IT + ? (sum of last two)
if($v==='+'){
//get last TWO entries from $result. (returns an array)
$last=array_slice($result,-2);
//sum of $lasttwo
$result[]=array_sum($last);
continue;
}
//IS IT C ? (remove last)
if($v==='C'){
//remove the last entry from $result
array_pop($result);
continue;
}
//IS IT D ? (last * 2)
if($v==='D'){
//get last entry from $result
$last=end($result);
$result[]=$last*2;
continue;
}
}
//get the TOTAL
$total=array_sum($result);
echo implode(', ',$result).' = '.$total;
I want to leave duplicates inside my array and only delete one occurrence when a value is found more than once.
Given an array of:
$array = ['+5', '+5', '+3', '+3', '+3', '+3', '+5', '+5'];
+5 and +3 each occur four times. I want to remove just one of the +5 values and just one of the +3 values, then find the sum of the remaining values.
$duplicate = ['+5', '+3'];
$array = ['+5', '+5', '+3', '+3', '+3', '+3', '+5', '+5'];
$i = 0;
foreach ($duplicate as $dup) {
if (strpos($duplicate[$i], '+') !== false) {
$duplicate[$i] = preg_replace('/[^0-9,:]/', '', $duplicate[$i]);
$duplicate[$i] = "-$duplicate[$i]";
}
$i++;
}
$sum = array_merge($duplicate, $array);
$end_value = array_sum(array_values($sum));
var_export($end_value);
For my input, the final sum should be 24 (15 + 9).
You need to remember what value you deleted from the array.
In below script you save te value if it apperas at the first time, in $existsValues array. If you find the same value again you delete it (and save information that you did it in $deletedValues array). If value exists in both arrays then you just do nothing with it. In this way you delete always the second occurence of the value and nothing more.
$existsValues = [];
$deletedValues = [];
foreach ($add_array as $key => $value) {
if (!in_array($value, $existsValues)) {
$existsValues[] = $value;
} else {
if (!in_array($value, $deletedValues)) {
$deletedValues[] = $value;
unset($add_array[$key]);
}
}
}
The task of summing all values and omitting just one occurrence of all repeated values can be done without conditionally maintaining a duplicate array and definitely doesn't require regex.
Code: (Demo)
$array = ['+5', '+5', '+3', '+3', '+3', '+3', '+5', '+5'];
foreach (array_count_values($array) as $value => $count) {
if ($count > 1) {
unset($array[array_search($value, $array)]);
}
}
var_export(array_sum($array)); // 24
The above groups values and counts their occurrences. Then it removes just one of the values when the values occurs more than once. Then sum the altered array.
Or you can boil it down to a mathematical process: (Demo)
$total = 0;
foreach (array_count_values($array) as $value => $count) {
$total += $value * ($count - ($count > 1));
}
echo $total;
// 24
^ if the count is greater than 1, subtract 1 from the multiplier. (if $count > 1, then true is treated as 1; otherwise 0).
I am a rookie beginner with PHP, i was wondering how i could add up the total number from 1 array + the total number of another array together. I managed to make this code with help from stackoverflow answers on google. I don't know why but it's no where explained or i am looking over it. Been looking for almost an hour to make this work. Here is the code:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
echo '<b>Oneven</b> ';
print_r($odds);
echo '<br><br><br>';
echo "Bovenstaande <b>oneven</b> getallen bijelkaar opgeteld = " . array_sum($odds) . "\n";
echo '<br><br><br><hr style="margin-top:2%;margin-bottom:4%;">';
/* Array nummer 2 */
$array = array(20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
echo '<b>Even</b> ';
print_r($even);
echo '<br><br><br>';
echo "Bovenstaande <b>even</b> getallen bijelkaar opgeteld = " . array_sum($even) . "\n";
?>
So i don't know how to do it in another way but i have array 1 code at first and then code 2 begins with another array.
The thing is that i want to make a program that includes the odd numbers from 1 to 19 and the even numbers from 20 to 40 and then count the total of those 2 array's. Is there a way to do this in 1 code and count up the total of those 2 array's together. I already have that part of code that it counts the array, in code 1 that is 100 and in code 2 it is 330.
330+100=430 that's the output that i want. Why is that so hard? haha...
I appreciate the help and time effort.
First off, there's a lot of complexity involved in creating the initial array and then extracting only the odd numbers. This complexity can be eliminating by using the range and array_filter functions like so:
$odds = array_filter(range(1, 19), function($elem) {
return $elem & 1;
});
$even = array_filter(range(20, 40), function($elem) {
return $elem % 2 == 0;
});
to calculate sum of the sum of odds plus the sum of even, you can simply merge them together and use array_sum in the same you are doing for the individual arrays
$totalSum = array_sum(array_merge($odds, $even))
As #Darragh pointed out in the comments, you can simplify the array creation by specifying a step parameter for the range function.
$odds = range(1, 19, 2) // start at 1, go up to 19, by increments of 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