I am calculating and getting result and array from a function in a foreach loop and do min() or max() on that result but the result is wrong. Can someone explain to me why? Thanks
function subtract($a, $b){
$c=$b-$a;
return $c. ',';
}
$r=3;
$numbers = array(12, 11, 6, 9, 15);
foreach ($numbers as $index=>$value) {
$deductions[]=array(subtract($r, $value));
$minimum=min($deductions);
}
print_r($minimum);
I get 12 instead of 3 in this case.
function subtract($a, $b){
$c=$b-$a;
return $c;
}
$r=3;
$numbers = array(12, 11, 6, 9, 15);
foreach ($numbers as $index=>$value) {
$deductions[]=array(subtract($r, $value));
$minimum=min($deductions);
}
echo min($minimum);
You can use array_walk as Rizier123 already showed the way along with the array_map
$r=3;
$numbers = array(12, 11, 6, 9, 15);
array_walk($numbers,function($v,$k) use(&$result,$r){ $result[$k] = $v-$r;});
print_r(min($result));
Related
My task is to create a loop that displays all even numbers in a column and it also displays a sum of all odd numbers in an array.
So far I have made this:
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
}
?>
This code successfully displays a list of all even numbers. However, I still have to include a sum of all odd numbers that is displayed below the list of evens. For some reason, I am supposed to use a variable $sumOdd = 0.
How do I approach this from here on?
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = 0;
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
} else {
$sumOdd += $value
}
}
echo $sumOdd;
To do it backwards: add all numbers, take out the even ones
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sum = array_sum($numbers);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
$sum = $sum - $value;
}
echo 'odds: '. $sum;
?>
heyo,
the $sumOdd = 0; should be before the foreach, inside the foreach you will do another check and if it's odd you add the number on $sumOdd += $value
this is a short and cleaner answer :
$sumOdd = 0;
foreach (range(1, 10) as $number) {
if (0 === $number % 2) {
echo $number . '<br>';
continue;
}
$sumOdd += $number;
}
echo '<br> sumOdd = '.$sumOdd;
A better way to calculate the sum is to pass the result of array_filter to array_sum. By doing that, you separate the tasks (calculate, display) and the code becomes more clean and maintainable.
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = array_sum(array_filter($numbers, function($v) {
return $v % 2 !== 0;
}));
I have a loop which i made like this:
$arr = array(1, 2, 3, 4, 5, 6, 7);
foreach ($arr as &$value) {
echo $value;
}
My loop result shows this:
1234567
I would like this to only show the numbers 1 to 4.
And when it reaches 4 it should add a break and continue with 5671.
So an example is:
1234<br>
5671<br>
2345<br>
6712<br>
I have to make this but I have no idea where to start, all hints/tips are very welcome or comment any direction I should Google.
Here is more universal function- you can pass an array as argument, and amount of elements you want to display.
<?php
$array = array(1,2,3,4,5,6,7);
function getFirstValues(&$array, $amount){
for($i=0; $i<$amount; $i++){
echo $array[0];
array_push($array, array_shift($array));
}
echo "<br />";
}
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
?>
The result is:
1234
5671
2345
6712
This produces the exact results you want
$arr = array(1, 2, 3, 4, 5, 6, 7);
$k=0;
for($i=1;$i<=5;++$i){
foreach ($arr as &$value) {
++$k;
echo $value;
if($k %4 == 0) {
echo '<br />';
$k=0;
}
}
}
You are looking for array_chunk()
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
$chunks = array_chunk($arr, 4);
foreach ($chunks as $array) {
foreach ($array as $value) {
echo $value;
}
echo "<br />";
}
The output is:
1234
5678
9101112
13
I was trying to create a PHP function that multiplies the values/content of the array by a given argument.
Modify this function so that you can pass an additional argument to this function.
The function should multiply each value in the array by this additional argument
(call this additional argument 'factor' inside the function).
For example say $A = array(2,4,10,16). When you say
$B = multiply($A, 5);
var_dump($B);
this should dump B which contains [10, 20, 50, 80 ]
Here's my code so far:
$A = array(2, 4, 10, 16);
function multiply($array, $factor){
foreach ($array as $key => $value) {
echo $value = $value * $factor;
}
}
$B = multiply($A, 6);
var_dump($B);
Any idea? Thanks!
Your function is not right, It has to return that array and not echo some values.
function multiply($array, $factor)
{
foreach ($array as $key => $value)
{
$array[$key]=$value*$factor;
}
return $array;
}
Rest is fine.
Fiddle
You can even do this with array_map
$A = array(2, 4, 10, 16);
print_r(array_map(function($number){return $number * 6;}, $A));
Fiddle
A simpler solution where you don't have to iterate over the array yourself but instead use php native functions (and a closure):
function multiply($array, $factor) {
return array_map(function ($x) {return $x * $factor}, $array);
}
$myArray = [2, 3, 5];
$factor = 3;
array_walk($myArray, function(&$v) use($factor) {$v *= $factor;});
// $myArray = [6, 9, 15];
or like this if no $factor variable requared
array_walk($myArray, function(&$v) {$v *= 3;});
$A = array(2, 4, 10, 16);
function multiply($array, $factor){
foreach ($array as $key => $value) {
$val[]=$value*$factor;
}
return $val;
}
$B = multiply($A, 6);
var_dump($B);
I was just going through these questions for PHP and got stuck at one of them. The question is:
You have a PHP 1 dimensional array. Please write a PHP function that
takes 1 array as its parameter and returns an array. The function must
delete values in the input array that shows up 3 times or more?
For example, if you give the function
array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9)the function will returnarray(1, 3, 5, 2, 3, 1, 9)
I was able to check if they are repeating themselves but I apply it to the array I am getting as input.
function removeDuplicate($array){
$result = array_count_values( $array );
$values = implode(" ", array_values($result));
echo $values . "<br>";
}
$qArray = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
removeDuplicate($qArray);
One more thing, we cannot use array_unique because it includes the value which is repeated and in question we totally remove them from the current array.
Assuming the value may not appear 3+ times anywhere in the array:
$array = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
// create array indexed by the numbers to remove
$remove = array_filter(array_count_values($array), function($value) {
return $value >= 3;
});
// filter the original array
$results = array_values(array_filter($array, function($value) use ($remove) {
return !array_key_exists($value, $remove);
}));
If values may not appear 3+ times consecutively:
$results = [];
for ($i = 0, $n = count($array); $i != $n;) {
$p = $i++;
// find repeated characters
while ($i != $n && $array[$p] === $array[$i]) {
++$i;
}
if ($i - $p < 3) {
// add to results
$results += array_fill(count($results), $i - $p, $array[$p]);
}
}
This should work :
function removeDuplicate($array) {
foreach ($array as $key => $val) {
$new[$val] ++;
if ($new[$val] >= 3)
unset($array[$key]);
}
return $array;
}
run this function i hope this help..
function removeDuplicate($array){
$result = array_count_values( $array );
$dub = array();
$answer = array();
foreach($result as $key => $val) {
if($val >= 3) {
$dub[] = $key;
}
}
foreach($array as $val) {
if(!in_array($val, $dub)) {
$answer[] = $val;
}
}
return $answer;
}
You can use this function with any number of occurrences you want - by default 3
function removeDuplicate($arr, $x = 3){
$new = $rem = array();
foreach($arr as $val) {
$new[$val]++;
if($new[$val]>=$x){
$rem[$val]=$new[$val];
}
}
$new = array_keys(array_diff_key($new, $rem));
return $new;
}
I think it is getting correct output. just try once.
$array=array(1,2,3,7,4,4,3,5,5,6,7);
$count=count($array);
$k=array();
for($i=0;$i<=$count;$i++)
{
if(!in_array($array[$i],$k))
{
$k[]=$array[$i];
}
}
array_pop($k);
print_r($k);
in this first $k is an empty array,after that we are inserting values into $k.
You should use array_unique funciton.
<?php
$q = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
print_r(array_unique($q));
?>
Try it and let me know if it worked.
I have an array which looks something like this:
array(-2, -1, 0, 1, 2, 3, 4)
I would like to count the number of negative numbers only. I can't spot where it says how to do this in the manual, is there no function to do this? Do I have to create a loop to go through the array manually?
Do I have to create a loop to go through the array manually?
Yes, you have to do it manually by easily doing:
function count_negatives(array $array) {
$i = 0;
foreach ($array as $x)
if ($x < 0) $i++;
return $i;
}
At the end of the script $i will contain the number of negative numbers.
I should use this:
$array = array(-2, -1, 0, 1, 2, 3, 4);
function negative($int) {
return ($int < 0);
}
var_dump(count(array_filter($array, "negative")));
You can use array_filter
function neg($var){
if($var < 0){
return $var;
}
}
$array1 = array(-2, -1, 0, 1, 2, 3, 4);
print count(array_filter($array1, "neg"));
Use array_filter http://www.php.net/manual/en/function.array-filter.php
function isnegative($value){
return is_numeric($value) && $value < 0;
}
$arr = array_filter(array(-1,2,3,-4), 'isnegative');
echo length($arr);
Have fun.
Try this:
$aValues = array(1, 2, 3, -1, -2, -3, 0);
echo sizeof(array_filter($aValues, create_function('$v', 'return $v < 0;')));