PHP Array Combine and Sum - php

I have multiple arrays, that get generated when a for loop completes. Now I need to get the total of all these arrays together, but in order, for instance:
array1(2, 4, 6, 8, 10)
array2(2, 4, 6, 8, 10)
I need to add the 2's together, the 4's etc etc
Then put them into another array.
Some combination of array_combine and array_sum seems to be the solution but I can't figure it out.
Any help is greatly appreciated.

You could do this without any php function except count,
$limit = count($array1);
for ($i = 0; $i < $limit; $i++) {
$array_res[$i] = $array1[$i] + $array2[$i];
should work. This will combine your two arrays and add them in the same order. But be sure you used sort or ksort on both of your arrays before if you're not sure they are in the same order.

1st stlye
$a1 = array(
"a" => 2
,"b" => 0
,"c" => 5
);
$a2 = array(
"a" => 3
,"b" => 9
,"c" => 7
,"d" => 10
);
$a3 = array_merge($a1, $a2);
print_r($a3);
2nd style
$a3 = $a1;
foreach($a2 as $k=>$v) {
if(array_key_exists($k,$a3))
$a3[$k] + = $v;
else
$a3[$k] = $v;
}

You should use array_map():
$arr1 = array(2, 4, 6, 8, 10);
$arr2 = array(1, 2, 3, 4, 5);
$arr3 = array_map(
function($foo, $bar){
return $foo+$bar;
},
$arr1, $arr2
);
print_r($arr3); // outputs:
Array
(
[0] => 3
[1] => 6
[2] => 9
[3] => 12
[4] => 15
)

You can do something like this
$a = array(2, 4, 6, 8, 10);
$b = array(2, 4, 6, 8, 10);
$c = array_map("test", $a, $b);
function test($a, $b) {
return $a + $b;
}
print_r($c);

As far as I understand your question You want sum of all the similar digits in both the array:
<?php
$array1= array(2, 4, 6, 8, 10);
$array2=array(2, 4, 6, 8, 10);
$array_sum=array();
foreach($array1 as $key1=>$val1)
{
$sum=0;
foreach($array2 as $key2 => $val2)
{
if($val1==$val2)
{
$sum=$sum+$val1;
}
}
$array_sum[]=$sum;
}
print_r($array_sum);
?>

Related

PHP: different elements between two arrays

I have two different arrays like this
$array1 = [1, 2, 8, 10];
$array2 = [2, 4, 6, 8, 10, 15, 1];
I want to get the common elements and uncommon elements between them.
I almost figured out how to get the common ones as the code below but I can't get uncommon elements.
for($x = 0; $x < count($array1); $x++) {
for($z = 0; $z < count($array2); $z++) {
if ( $array1[$x] == $array2[$z] ) {
$array3 = $array1[$x];
print_r($array3);
} elseif ($array1[$x] !== $array2[$z]) {
// code...
}
}
}
How to get those uncommon or different elements between the two arrays without using a built-in PHP method then output them in a new array.
You can get the uncommon elements by using in_array() function
<?php
$array1 = [1, 2, 8, 10];
$array2 = [2, 4, 6, 8, 10, 15, 1];
$result = [];
for($i = 0;$i < sizeof($array2);$i++){
if(!in_array($array2[$i],$array1)){
$result[] = $array2[$i];
}
}
?>
Output
Array
(
[0] => 4
[1] => 6
[2] => 15
)

Map/Merge data from a flat array into the rows of a 2d array [duplicate]

This question already has answers here:
Push elements from one array into rows of another array (one element per row)
(4 answers)
Closed 5 months ago.
I want to add the values of array b to array a:
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
Result should be:
$result = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
I am trying this (and lots of other stuff) but don't get it.
foreach ($a as $el) {
$i = 0;
$el[] = $b[$i];
$i++;
}
Here we are using array_walk to achieve desired output. Hope this will be helpful.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
array_walk($a,function(&$value,$key) use($b){
array_push($value, $b[$key]);
});
print_r($a);
This should be as simple as:
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
foreach($a as $key => &$arr){
$arr[] = $b[$key];
}
This is not hard.
<?php
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
for($i = 0; $i < count($b);$i++) {
array_push($a[$i],$b[$i]);
}
?>
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
$result = $a;
foreach ($a as $key => $val) {
if(!empty($b[$key])) {
array_push($result[$key], $b[$key]);
}
}
var_export($result);
Here is the clever one-liner that no one else thought of:
Code: (Demo)
$a = [[1, 2],[4, 5],[7, 8]];
$b = [3, 6, 9];
var_export(array_map('array_merge',$a,array_chunk($b,1)));
Output:
array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
),
1 =>
array (
0 => 4,
1 => 5,
2 => 6,
),
2 =>
array (
0 => 7,
1 => 8,
2 => 9,
),
)
This approach splits $b into the same structure as $a, then it is simple to merge them together.
If your input arrays are relatively small, a foreach() is probably the best choice. As your input array grows in size, I believe you will find that my approach will have increasing performance benefits over foreach() (though I'll be honest I am basing this on other similar answers I have provided and I haven't actually benchmarked this case).

Count element in multidimensional array

I have one problem with PHP array. I have the following array:
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
I want to know how many element in total.
Ex:
echo count($arr); // result: 3
but I want: 7
I want to do this without loop.
Do any one know, please help?
Take one of this
$arr = array(
1 => array(1, 2),
2 => array(1, 2, 3),
3 => array(4, array(4, 4, 4))
);
// iterate over values to find out their size/
var_dump(array_reduce($arr, function($count, $inner_array)
{ return $count + sizeof($inner_array); }, 0));
// merge all value to one big array
var_dump(count(call_user_func_array('array_merge', $arr)));
// create new array with counts of items
var_dump(array_sum(array_map('sizeof', $arr)));
<?php
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
$sum = 0;
foreach($arr as $a => $b) {
$sum += count($b);
}
echo $sum;
?>
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,array(4,4,4))
);
$count = 0;
foreach ($arr as $level) {
$count+= count($level);
}
echo $count;
If your array as follows you can use another method for get 7
$arr = array(
1 => array(1, 2),
2 => array(1,2,3),
3 => array(4,8)
);
echo (count($arr, COUNT_RECURSIVE) - count($arr));

remove elements in php array that occur more than twice

I am looking for a function in php,where the function must delete values in the array that shows up three times or more? For example, if you give the function array(2, 4, 6, 3, 7, 7, 7, 4, 2, 0) the funciton will return array(2, 4, 6, 3, 4, 2, 0)
You can use array_count_values() to get frequencies. Then use a foreach to get values that has frequency less than 3...
$array = array(2, 4, 6, 3, 7, 7, 7, 4, 2, 0);
$frq = array_count_values($array);
$result = array();
foreach ($frq as $key=>$value){
if ($value < 3){
$result[] = $key;
}
}
function FilterMyArray(array &$array){
$array_count=array_count_values($array);
foreach($array_count as $key => $value){
if($value > 2){
foreach (array_keys($array, $key, true) as $unsetKey) {
unset($array[$unsetKey]);
}
}
}
}
$array=array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
FilterMyArray($array);
print_r($array);
Output
Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 2 [7] => 3 [8] => 1 [9] => 9 )
`
This will remove all duplicates, but you'd have to add to it to count the number of each of the values.
$a = array(2, 4, 6, 3, 7, 7, 7, 4, 2, 0);
$b = array();
for ($a as $key=>$value) {
if (!in_array($value, $b)) {
$b[] = $value;
}
}
// array $b has all the values with no duplicates.

Merge two flat arrays and omit values from one array when the other array has more occurrences of the same value

I want to merge every element of two arrays, BUT if a value is in both arrays, then only add the values from the array which has the biggest amount of that element. The result array does not need to be sorted in any special way, but I did it here for readability.
Sample input:
$array1 = [1, 4, 7, 3, 3, 3];
$array2 = [4, 0, 3, 4, 9, 9];
Desired result:
[0, 1, 3, 3, 3, 4, 4, 7, 9, 9]
//a2 a1 a1 a1 a1 a2 a2 a1 a2 a2
Note, this will be used on big arrays, with unknown integer values. Is there a good way to do this that doesn't require too much time/processing power?
Try this:
<?php
$array1 = [1, 4, 7, 3, 3, 3];
$array2 = [4, 0, 3, 4, 9, 9];
function min_merge($arr1, $arr2) {
$arr1 = array_count_values($arr1);
$arr2 = array_count_values($arr2);
foreach ($arr2 as $index => $arr)
if (!isset($arr1[$index]) || $arr > $arr1[$index])
$arr1[$index] = $arr;
foreach ($arr1 as $index => $arr)
for ($i = 0; $i < $arr; $i++)
$final[] = $index;
return $final;
}
print_r(min_merge($array1, $array2));
Output:
Array (
[0] => 1
[1] => 4
[2] => 4
[3] => 7
[4] => 3
[5] => 3
[6] => 3
[7] => 0
[8] => 9
[9] => 9
)
Unsorted, but it contains all the numbers from [0, 1, 3, 3, 3, 4, 4, 7, 9, 9].
$count[0] = array_count_values($arr1);
$count[1] = array_count_values($arr2);
$out = array();
array_map(function($e) use(&$out, $count){
$n1 = (isset($count[0][$e])) ? $count[0][$e] : 0;
$n2 = (isset($count[1][$e])) ? $count[1][$e] : 0;
$next = ($n2 > $n1) ? array_fill(0, $n2, $e) : array_fill(0, $n1, $e);
$out = array_merge($out, $next);
}, array_keys($count[0] + $count[1]));
print_r($out);
My modernized rewrite of #DaveChen's answer using PSR-12 coding standards and eliminating single-use declarations. This approach uses one loop to determine the greater count for numbers shared by both value-count arrays, then a second loop to populate the result array. (Demo)
$counts1 = array_count_values($array1);
foreach (array_count_values($array2) as $number => $count) {
if ($count > ($counts1[$number] ?? 0)) {
$counts1[$number] = $count;
}
}
$result = [];
foreach ($counts1 as $number => $count) {
array_push($result, ...array_fill(0, $count, $number));
}
var_export($result);
My modernized rewrite of #Expedito's answer which does not abuse the array_map() (when array_map()'s return value is not used, use array_walk() for functional style programming), uses a foreach() loop to eliminate variable scope issues, and generally implements D.R.Y. techniques. (Demo)
$counts1 = array_count_values($array1);
$counts2 = array_count_values($array2);
$result = [];
foreach ($counts1 + $counts2 as $num => $cnt) {
array_push(
$result,
...array_fill(
0,
max($counts1[$num] ?? 0, $counts2[$num] ?? 0),
$num
)
);
}
var_export($result);
And I wanted to add a new approach of my own, despite the fact that it may or may not perform better than the other two snippets. The script makes one pass over the first value count arrays to populate a temporary array which demands which numbers from the first array should be represented in the result array. Then it isolates value intersections from the first array, value differences from the second array, then merges them. (Demo)
$counts1 = array_count_values($array1);
$counts2 = array_count_values($array2);
$keepFrom1 = array_keys(
array_filter(
$counts1,
fn($count, $number) => ($counts2[$number] ?? 0) <= $count,
ARRAY_FILTER_USE_BOTH
)
);
var_export(
array_merge(
array_intersect($array1, $keepFrom1),
array_diff($array2, $keepFrom1)
)
);
probably not the most optimized but
<?php
$one=[1, 4, 7, 3, 3, 3];
$two=[4, 0, 3, 4, 9, 9];
sort($one);
sort($two);
foreach($one as $el)
{
$combined[]=$el;
if (array_search($el,$two))
{
unset($two[array_search($el,$two)]);
}
}
foreach($two as $el)
{
$combined[]=$el;
}
sort($combined);
print_r($combined);
?>

Categories