Pairwise subtraction of two arrays - php

There are two arrays:
$arr1 = array(1,2,3);
$arr2 = array(0,0,1);
I need to make pairwise subtraction of these two arrays. The result for arr1 - arr2 should be:
$arr3 = array(1,2,2).
Do I need to use FOR loop to to this or is there any quicker way?

In addition to the other answers, you could also use array_map()
function sub($x, $y){
return $x - $y;
}
$arr3 = array_map('sub', $arr1, $arr2);

How about this function?
function array_sub_values($arr1, $arr2)
{
$result = array();
foreach ($arr1 as $k => $val)
$result[] = $val - $arr2[$k];
return $result;
}
So you can do:
$arr1 = array(1, 2, 3);
$arr2 = array(0, 0, 1);
$arr3 = array_sub_values($arr1, $arr2);

Related

How to replace array value with another array value using php?

I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}

PHP array doubling digits

I have an array and I want to double it but after executing the array doesn't change how to correct it as minimally as possible.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
Your values didn't double because you're not saying the key should be overwritten in $arr this code should be working:
$arr = array(1,2,3,4);
foreach($arr as $key => $value){
$arr[$key] = $value*2;
}
An alternative would be to use array_map().
<?php
function double($i){
return $i*2;
}
$arr = array(1, 2, 3, 4);
$arr = array_map('double', $arr);
var_dump($arr);
?>
You need to double the actual array $arr element, not just the value in the cycle.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
$arr[$key] = $value * 2;
}
?>
You are using a variable $value which is assigning in each for loop so this value stored in $value is overwrithing in your foreach loop. You have
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
This will work
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
print_r($arr);
?>
short solution, and supported in < PHP 5.3, try this code
<?php
$arr = array(1, 2, 3, 4);
$arr = array_map(create_function('$v', 'return $v * 2;'), $arr);
print_r($arr);
DEMO
Try the following code:
$arr = array(1, 2, 3, 4);
array_walk($arr, function(&$item){
$item*=2;
});
var_dump($arr);

PHP merging arrays uniquely

So i'm working on a small php applications that combines four arrays.
Now there is a possibility that some of the possible arrays will be null.
I tried the following solution to merge the four arrays uniquely.
<?php
$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];
$new_array;
if(is_array($a) && is_array($b) && is_array($c) && is_array($d))
{
$new_array = array_unique(array_merge($a,$b,$c,$d));
}else if(is_array($a) && is_array($b) && is_array($c))
{
$new_array = array_unique(array_merge($a,$b,$c));
}else if(is_array($a) && is_array($b))
{
$new_array = array_unique(array_merge($a,$b));
}else{
$new_array = $a;
}
print_r($new_array);
?>
I soon realized my code was highly dysfunctional in that it does not cater for all possible combinations of arrays while excluding the null variables.
How do I solve this. Ensuring that all the variables that are arrays are merged a nd those that are not are discarded.
Thanks
how about this? putting all the array's in an array, so you can loop through them all easily, and use a custom in_array() function to check if they are already existing?
The good thing about this way is that it doesn't limit the script to just four array's, as it will loop through all the array's you get together.
$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];
$array_stack = array($a, $b, $c, $d);
$new_array = array();
foreach($array_stack as $stack){
if(!is_array($stack)) continue;
foreach($stack as $value){
if(!in_array($value, $new_array)) $new_array[] = $value;
}
}
print_r($new_array);
maybe something like this :
<?php
$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];
$new_array;
if(is_array($a)) $new_array = $a;
if(is_array($b)) $new_array = array_unique(array_merge($new_array,$b));
if(is_array($c)) $new_array = array_unique(array_merge($new_array,$c));
if(is_array($d)) $new_array = array_unique(array_merge($new_array,$d));
?>
Old question, but going to give my input anyways. A more universal approach:
function multiple_array_merge() {
$args = func_get_args();
$array = [];
foreach ($args as $i) {
if (is_array($i)) $array = array_merge($array, $i);
}
return array_unique($array);
}
$a = [1, 2, 3, 4, 5];
$b = null;
$c = [5, 4, 3, 2, 1];
$d = [1, 2];
$merged = multiple_array_merge($a, $b, $c, $d);

Filter or Sorting multidimensional arrays in PHP

If i have two array as following:
$array1 = array(array('id'=>11,'name'=>'Name1'),array('id'=>22,'name'=>'Name2'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'),array('id'=>55,'name'=>'Name5'));
$array2 = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'));
My expect result, the array2 should be always at the beginning :
$newarray = array(array('id'=>22,'name'=>'Name2'),array('id'=>55,'name'=>'Name5'), array('id'=>11,'name'=>'Name1'), array('id'=>33,'name'=>'Name3'),array('id'=>44,'name'=>'Name4'));
My current solution is using two for loops:
foreach($array2 as $Key2 => $Value2) {
foreach($array1 as $Key1 => $Value1){
if($Value1['id'] != $Value2['id']) {
//push array
}
}
}
Edit:
The result "$newarray" should not include the duplicate ids from array1.
But i am looking for a faster and simpler solution.
SOLUTION:
$a1 = array();
foreach ($array1 as $v) $a1[$v['uuid']] = $v;
$a2 = array();
foreach ($array2 as $v) $a2[$v['uuid']] = $v;
$filtered = array_values(array_diff_key($a1, $a2));
//print_r($filtered);
$newarray = array_merge($array2, $filtered);
Thank you guys!!!!
Thanks.
Regards Jack
you want $new_array = array_merge($array2, $array1); puts the second array onto the end of the first one
You can use array_merge() function for that, like this:
$newarray = array_merge($array2, $array1);
I am not sure about your requirement but to sort multi-dimensional array on some specific key
You need to use usort function
Try the code below:
$cmp = function ($a, $b){
$a_val = $a['id'];
$b_val = $b['id'];
if ( $a_val == $b_val) {
return 0;
}
return ($a_val < $b_val) ? -1 : 1;
};
usort($array2,$cmp);
$array2 will be sorted by 'id'

Repeat array to a certain length?

I'm having an array for example with 4 elements array("a", "b", "c", d"); what is the fastest way to repeat this array to create a new array with a certain length, e.g 71 elements?
// the variables
$array = array("a", "b", "c", "d");
$desiredLength = 71;
$newArray = array();
// create a new array with AT LEAST the desired number of elements by joining the array at the end of the new array
while(count($newArray) <= $desiredLength){
$newArray = array_merge($newArray, $array);
}
// reduce the new array to the desired length (as there might be too many elements in the new array
$array = array_slice($newArray, 0, $desiredLength);
Solution using SPL InfiniteIterator:
<?php
function fillArray1($length, $values) {
foreach (new InfiniteIterator(new ArrayIterator($values)) as $element) {
if (!$length--) return $result;
$result[] = $element;
}
return $result;
}
var_dump(fillArray(71, array('a', 'b', 'c', 'd')));
The real SPL hackers might have dropped the if (!$length--) break; and instead used a limit iterator: new LimitIterator(new InfiniteIterator(new ArrayIterator($values)), 0, $length), but I thought that to be overkill...
A simple solution using each() and reset() and the array's internal pointer:
<?php
$array = array('a', 'b', 'c', 'd');
$length = 71;
$result = array();
while(count($result) < $length)
{
$current = each($array);
if($current == false)
{
reset($array);
continue;
}
$result[] = $current[1];
}
echo count($result); // Output: 71
In order to join this club:
$result = call_user_func_array('array_merge', array_fill(0, ceil($size/count($array)), $array));
while(count($result) > $size) array_pop($result);
You asked for the fastest so I did a benchmark (Source: http://pastebin.com/G5w7QJPU)
Kau-Boy: 5.40128803253
Frxstrem: 5.00970411301
NikiC: 4.12150001526
user2469998: 0.561513900757
Alexander: 1.92847204208
Hammerite: 2.17130494118
Max: 12.9516701698
Evert: 1.9378361702
Christoph: 1.6862449646
Test took 35.7696909904s
user2469998 is the fastest but it only works for string values with single chars (or the same length if you use second parameter of str_split).
$newarray = array();
$i = 0;
$oldarrayvalues = array_values($oldarray);
$oldarraysize = count($oldarrayvalues);
if ( $oldarraysize ) {
while ( count($newarray) < DESIRED_ARRAY_SIZE ) {
$newarray[] = $oldarrayvalues[$i];
$i++;
$i %= $oldarraysize;
}
}
If you have PHP 5.3 available, you can also try this:
function fill(array $initalArray, $toCount) {
$initialArrayCount = count($initalArray);
$fillUp = function(array $filledUpArray, $missingCount)
use(&$fillUp, $initalArray, $initialArrayCount, $toCount)
{
if($missingCount <= 0) return array_slice($filledUpArray, 0, $toCount);
return $fillUp(array_merge($filledUpArray, $initalArray), $missingCount - $initialArrayCount);
};
return $fillUp($initalArray, $toCount - $initialArrayCount);
}
$theArray = array("a", "b", "c", "d");
$toLength = 71;
$filledArray = fill($theArray, $toLength);
print_r($filledArray);
<?php
$array = array('a', 'b', 'c', 'd');
$end = 71;
$new_array = array();
while(count($new_array) <= $end)
{
foreach($array as $key => $value)
{
$new_array[] = $value;
}
}
$new_array = array_slice($new_array, 0, $end);
Tested and works.
You can test for yourself by adding this:
echo '<pre>';
print_r($new_array);
echo '</pre>';
$array = array("a", "b", "c", "d");
$merge = array();
$desiredLength = 71;
while(2 * count($array) <= $desiredLength){
$array = array_merge($array, $array);
}
if($desiredLength > count($array))
$merge = array_slice($array, 0, $desiredLength - count($array));
$array = array_merge($array, $merge);
$array = array_slice($array, 0, $desiredLength);
print_r($array);
$arr = array("a", "b", "c", "d");
$len = 71;
$a = array();
$a = str_split( substr( str_repeat( join( $arr), ceil( $len / count( $arr))), 0, $len));
var_export($a);
I think that user2469998 was closest but just not that nice.
For my example, I use pipe to implode and the str_repeat function to build a string that meets the length, explode it back apart and trim the fat.
$list = array('a','b','c','d');
$length = 6;
$result = array_slice(explode('|', str_repeat(implode('|', $list).'|',ceil($length/count($list)))), 0, $length);
Many ways to achieve this but thought I'd share mine. The only restriction is that you need to use a character to implode and explode on which isn't part of the array items or the exploder won't work properly.
:)

Categories