$amount = 2;
$array = array(3,6,12);
foreach($array as $a){
$total = $a*$amount;
}
result for only the last element:
int(24) int(12)
result must be:
int(6)
int(12)
int(24)
I want to calculate a sum of all the elements in the array, but only the last element is calculated.
Iterate over each element of the array passed as reference and update inside the loop, like this:
$amount = 2;
$array = array(3,6,12);
foreach($array as &$a){
$a = $a*$amount;
}
var_dump($array);
If you say that you want calculate sum elements of array $amount isn't neccesary.
You can use array_reduce You can see documentation here
function sumArray($carry, $item)
{
$carry += $item;
return $carry;
}
array_reduce($array, "sumArray");
if you need get array with (6,12,24) you can use
function sumArray($item)
{
return $item*2;
}
array_map("sumArray",$array); //array(6,12,24)
If this is indeed your code you should get a lot of undefined errors. You say that you want to get the sum, so why are you multiplying with $amount?
You want to do this:
<?php
$array = array(3,6,12);
$total = 0;
foreach($array as $a){
$total += $a;
}
Or even easier:
Just use array_sum:
array_sum — Calculate the sum of values in an array
Like so:
<?php
$array = array(3,6,12);
echo array_sum($array);
use array_map:
function double($v)
{
return $v * 2;
}
$a=array(3, 6, 12);
$resArr = array_map("double" ,$a));
the result will be an array [6, 12, 24]
Related
The dump of the following array is:
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) }
As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).
I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
And the same with id :
$id1= $quest_all[0];
$id2= $quest_all[1];
Any help is appreciated.
Try as below:
One way is:
array_values($quest_all); will give you an array of all Ids
array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.
Other way, First get all qcounters only from collection:
$quest_all = $qwinners->pluck('qcounter')->toArray();
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
...
and so on
Then get all ids
$quest_all = $qwinners->pluck('id')->toArray();
$id1= $quest_all[0];
$id2= $quest_all[1];
...
and so on
You can also use foreach to iterate through the result array.
To reset array keys, use array_values().
To get array keys, use array_keys():
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
$quest_all_keys = array_keys($quest_all);
$quest_all_values = array_values($quest_all);
Or simply use foreach():
$keys = [];
$values = [];
foreach($quest_all as $key => $value){
$keys[] = $key;
$values[] = $value;
}
I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)
$quest_all = ...;
$count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
// $qcounter_0 $qcounter_1
// $id_0 $id_1
for ($i = 0; $i < $count; $i++) {
echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
}
It would probably be easier to just have the 2 arrays:
$keys = array_keys($quest_all);
$values = array_values($quest_all);
I have 2 arrays.
arr1 =array('cat'=>5,'dog'=>2);
arr2 = array('cat'=>1,'dog'=>2);
I need to get the sum of 2 arrays and the difference of these arrays.
arr3 = array(cat =>6,dog =>4);
arr4 = array(cat =>4 ,dog =>0);
I tried USING array_merge,array_diff,array_combine
But nothing gives me what i need.
plz help
Assuming we have the same number of like keys in both arrays we can iterate through one or the other and find and work with the corresponding values belonging to the other identified by the same named keys.
<?php
$a1 = array('cat'=>5,'dog'=>2);
$a2 = array('cat'=>1,'dog'=>2);
foreach($a1 as $k => $v)
{
$add[$k] = $v + $a2[$k];
$sub[$k] = $v - $a2[$k];
}
var_dump($add, $sub);
Output:
array(2) {
["cat"]=>
int(6)
["dog"]=>
int(4)
}
array(2) {
["cat"]=>
int(4)
["dog"]=>
int(0)
}
You could always resolve the first problem with array_sum.
Second is more interesting, I'd solve it with an array_map. See it in action here
$subtracted = array_map(function ($x, $y) {
return $x - $y;
}, $arr1, $arr2);
$result = array_combine(array_keys($arr1), $subtracted);
Note that you can also solve the first problem by replacing - with + in the above example.
Also note that array_map tends to be generally more readable.
Simple foreach can do it, below example if some key is missing and just getting difference not in -ve Negative sign, the difference would be 4 not -4 for 1 cat - 5 cat
<?php
$arr1 =array('cat'=>5,'dog'=>2);
$arr2 = array('cat'=>1,'dog'=>2);
$sum= [];
$sub= [];
foreach(array_merge($arr1,$arr2) as $k=>$v){
$a1 = $arr1[$k] ?? 0;
$a2 = $arr2[$k] ?? 0;
$sum[$k] = $a1 + $a2;
$sub[$k] = abs($a1 - $a2);
}
print_r($sum);
print_r($sub);
?>
Live Demo
With simple foreach loop
If some data exist only in single array
Suppose I have the array $array where:
$array[0] = {'a','b','c'}
$array[1] = {'d','e','f'}
And I want to iterate over the first column of the nested array in order to get 'a','d' only. What is the most efficient way to do that other than having a loop that iterates on $array[n][0]?
For PHP < 5.3 you can use array_map function like as
$array[0] = ['a','b','c'];
$array[1] = ['d','e','f'];
echo implode(',',array_map(function($v){ return $v[0];},$array));//a,d
As #Rizier123 commented you can simply use array_shift as callback function like as
echo implode(',',array_map('array_shift',$array));//a,d
Demo
Try this -
$array[0] = ['a','b','c'];
$array[1] = ['d','e','f'];
$new = array_column($array, 0);
foreach($new as $v) {
echo $v . ' ';
}
Output
a d
For lower versions of PHP -
$new = array();
foreach($array as $a) {
$new[] = $a[0];
}
Is there any way to get the key range of same values and make a new array?
Let's say we have an Array Like this in php :
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b','6'=>'a','7'=>'a'];
How can i get this array? Is there any function for this?
$second_array = ['1-3'=>'a','4-5'=>'b','6-7'=>'a'];
Loop through it, extract the keys, generate the ranges and insert to the new array -
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
$flip = array();
foreach($first_array as $key => $val) {
$flip[$val][] = $key;
}
$second_array = [];
foreach($flip as $key => $value) {
$newKey = array_shift($value).' - '.end($value);
$second_array[$newKey] = $key;
}
Output
array(2) {
["1 - 3"]=>
string(1) "a"
["4 - 5"]=>
string(1) "b"
}
regarding your first question you can get range of each value using foreach() loop.
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
foreach($first_array as $key=>$value)
{
//do your coding here, $key is the index of the array and $value is the value at that range, you can use that index and value to perform array manipulations
}
Regarding your second question it not exactly clear what are trying to implement there. But what ever you want to do like creating a new array with modified index and other things can be done within this foreach() loop itself
I hope this helps you.
If someone is still looking for an answer, here is what I did.
Given the array
$first_array = ['0'=>'a',
'1'=>'a',
'2'=>'a',
'3'=>'a',
'4'=>'a',
'5'=>'b',
'6'=>'b',
'7'=>'a',
'8'=>'a']
I build a multidimensional array, in which each element is an array of three more elements:
[0] - The value in the first array
[1] - The key where the value starts repeating
[2] - The last key where the value stops repeating
The code
$arrayRange = [];
for($i = 0; $i < count($first_array); $i++){
if(count($arrayRange) == 0){
// The multidimensional array is still empty
$arrayRange[0] = array($first_array[$i], $i, $i);
}else{
if($first_array[$i] == $arrayRange[count($arrayRange)-1][0]){
// It's still the same value, I update the value of the last key
$arrayRange[count($arrayRange)-1][2] = $i;
}else{
// It's a new value, I insert a new array
$arrayRange[count($arrayRange)] = array($first_array[$i], $i, $i);
}
}
}
This way you get a multidimensional array like this:
$arrayRange[0] = array['a', 0, 4];
$arrayRange[1] = array['b', 5, 6];
$arrayRange[2] = array['a', 7, 8];
Have an array
array(array('a'=>'s','add'=>1),
array('a'=>'s1','add'=>2),
array('a'=>'s2','add'=>3)
...
...
);
I want to sum of all key add together.so result should be 6
Anyone know how to do this?
$sum = 0;
foreach($yourArray as $element) {
$sum += $element['add'];
}
echo $sum;
$sum = 0;
foreach($array1 as $array) {
$sum += $array['add'];
}
echo $sum; // will echo '6'
Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:
$total = 0;
foreach( $arrs as $arr )
{
$total += $arr['add'];
}
echo $total;
Where $arrs is the array you've defined above.
One liner echo array_sum(array_column($a, "add"));