I have to find the difference for both array, i have tried but i am not getting my expected.can you please help here.
<?php
$firstArray = array(3,4,5,6);
$secondArray = array(4, 5);
$outputArray = array();
foreach($firstArray as $firstArrayItem) {
foreach($secondArray as $secondArrayItem) {
if($firstArrayItem != $secondArrayItem) {
$outputArray[] = $firstArrayItem;
}
}
}
print_r($outputArray);
Expected output
[3,6]
Note: we should not use PHP inbuild functions.
a) Use a boolean value to check it:
<?php
$firstArray = array(3,4,5,6);
$secondArray = array(4, 5);
$outputArray = array();
foreach($firstArray as $firstArrayItem) {
$found = false;
foreach($secondArray as $secondArrayItem) {
if($firstArrayItem == $secondArrayItem) {
$found = true;
}
}
if($found == false){
$outputArray[] = $firstArrayItem;
}
}
print_r($outputArray);
Output: https://3v4l.org/8CuS8
b) Another way using for() loop: https://3v4l.org/9JZrW
Here is a solution that does not give a different result when the input arrays as swapped.
So it will give the same result for this:
$firstArray = array(3, 4, 5, 6);
$secondArray = array(4, 5);
as for this:
$firstArray = array(4, 5);
$secondArray = array(3, 4, 5, 6);
Also, it will deal with duplicate values as follows:
$firstArray = array(4, 4, 4);
$secondArray = array(3, 4, 6);
for which I would expect the output to be:
array(3, 4, 4, 6) // Only one 4 is common and should be excluded.
The code for having this behaviour could be (without inbuilt functions except for print_r):
$assoc = [];
foreach($firstArray as $value) {
$assoc[$value][] = 1;
}
foreach($secondArray as $value) {
$assoc[$value][] = -1;
}
foreach($assoc as $value => $list) {
$count = 0;
foreach($list as $delta) $count += $delta;
for($i = $count > 0 ? $count : -$count; $i > 0; $i--) {
$result[] = $value;
}
}
print_r($result);
$firstArray = array(3,4,5,6);
$secondArray = array(4, 5, 7);
$outputArray = diffArray($firstArray, $secondArray);
$outputArray = diffArray($secondArray, $firstArray, $outputArray);
function diffArray($arr1, $arr2, $result = array()) {
foreach($arr1 as $arr11) {
$isExist = false;
foreach($arr2 as $arr22) {
if($arr11 === $arr22) {
$isExist = true;
}
}
if(!$isExist) $result[] = $arr11;
}
return $result;
}
print_r($outputArray);
Related
$handle = fopen("googleshopping.csv", "r");
if ($handle)
{
while (($buffer = fgets($handle)) !== false)
{
$a=str_replace( array('[',']','(',')','"',"'") , '' , $buffer );
$array=explode(",",$a);
echo'<pre>';
print_r($array);
}
fclose($handle);
According to your comment:
You want to do this:
$y = 3; // number of nodes in each column or row. Change if needed.
$arr = array(); //the original one
$newArr = array();
$manipulationArr = array(); //this is an array to manipulate and use to get what you want in the $newArr
$x = 0;
foreach($arr as $e) {
$manipulationArr[] = $e;
$x = $x + 1;
if ($x == $y) {
$newArr[] = $manipulationArr;
$manipulationArr = array();
$x = 0;
}
}
unset($e);
This turns:
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
into:
$newArr = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
Though, that is row wise.
For the actual Column wise you need to do the row wise and then do this:
$newArr = array(); //row wise one
$columnWise = array();
$manipulation1 = array();
$manipulation2 = array(); // as many manipulation arrays as the value of $y
$manipulation3 = array();
$x = 0;
foreach ($newArr as $e) {
$manipulation1[] = $e[0];
$manipulation2[] = $e[1]; // the pattern continues based on the number of $manipulation arrays
$manipulation3[] = $e[2];
}
$columnWise[] = $manipulation1;
$columnWise[] = $manipulation2;
$columnWise[] = $manipulation3;
//pattern continues based on the number of $manipulation arrays
This means:
array(1, 2, 3, 4, 5, 6, 7, 8, 9) turns into:
array(
array(1, 4, 7),
array(2, 5, 8),
array(3, 6, 9)
)
second largest absolute value form array
input : array(13, -12, 8, 2, 5)
expected answer : 12
here is my code
<?php
function print2largest($arr, $arr_size)
{
if ($arr_size < 2)
{
echo(" Invalid Input ");
return;
}
$first = $second = PHP_INT_MIN;
for ($i = 0; $i < $arr_size ; $i++)
{
if ($arr[$i] > $first)
{
$second = $first;
$first = $arr[$i];
}
else if ($arr[$i] > $second &&
$arr[$i] != $first)
$second = $arr[$i];
}
if ($second == PHP_INT_MIN)
echo("There is no second largest element\n");
else
echo("The second largest element is " . $second . "\n");
}
$arr = array(13, -12, 8, 2, 5);
$n = sizeof($arr);
print2largest($arr, $n);
?>
output i got : 8
It can be easy done in "php-way":
$arr = array(13, -12, 8, 2, 5);
$absoluteArr = array_map('abs', array_unique($arr));
rsort($absoluteArr);
echo $absoluteArr[1];
No need to do that much code, do directly:
<?php
$array = array(13, -12, 8, 2, 5);
$final_array = array_unique(array_map('abs',$array)); // remove duplicates and apply abs() to all elements
rsort($final_array,SORT_NUMERIC); //reverse sort array numerically
echo $final_array[1]; //get second highest
Output:-https://3v4l.org/mgjaO
Reference:-
abs()
array_map()
array_unique()
rsort()
I'm not sure this needs a function, if you just rsort the array after each element has been updated with the absolute value with array_mapand look at the second position:
function print2largest($arr) {
if (count($arr) < 2) {
echo(" Invalid Input ");
return;
}
$arr = array_map("abs", $arr);
rsort($arr);
return $arr[1];
}
$arr = array(13, -11, 9, 2, 5);
print2largest($arr);
Just add abs() to the values here
function print2largest($arr, $arr_size)
{
if ($arr_size < 2)
{
echo(" Invalid Input ");
return;
}
$first = $second = PHP_INT_MIN;
for ($i = 0; $i < $arr_size ; $i++)
{
if (abs($arr[$i]) > $first)
{
$second = $first;
$first = abs($arr[$i]);
}
else if (abs($arr[$i]) > $second &&
abs($arr[$i]) != $first)
$second = abs($arr[$i]);
}
if ($second == PHP_INT_MIN)
echo("There is no second largest elementn");
else
echo("The second largest element is " . $second . "n");
}
$arr = array(13, -12, 8, 2, 5);
$n = sizeof($arr);
print2largest($arr, $n);
The second largest element is 12n
$array = [13, -12, 8, 2, 5];
echo getSecondLargestAbsolute($array); // 12
function getSecondLargestAbsolute($array)
{
$values = [];
if (count($array) == count($array, COUNT_RECURSIVE)) {
$values = $array;
} else {
foreach (new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array)) as $item) {
$values[] = $item;
};
}
array_walk($values, function (&$val){
return $val = abs($val);
});
rsort($values);
return $values[1];
}
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 want to merge / mix two arrays together, but I want it to be randomly "mixed" however NOT shuffled. For example:
$first = [1, 2, 3, 4];
$second = [10, 20, 30, 40];
Possible desired "mixes" are:
[1, 10, 20, 30, 2, 40, 3, 4]
[10, 1, 2, 20, 30, 3, 4, 40]
[1, 2, 3, 10, 20, 4, 30, 40]
Note that if we pluck the values back out we would still have the original orders of:
1, 2, 3, 4
10, 20, 30, 40
Well, there's (yet another) one possible approach:
$arr = call_user_func_array('array_merge', array_map(null, $first, $second));
print_r($arr); // [1, 10, 2, 20, 3, 30, 4, 40];
Demo. That's apparently deterministic; for random ordering each pair should be shuffled additionally. For example:
function zipShuffle($first, $second) {
return call_user_func_array('array_merge', array_map(function($a, $b) {
return mt_rand(0, 1) ? [$a, $b] : [$b, $a];
}, $first, $second));
}
... but that obviously won't be able to churn out something like [1,2,3,10,20...]. If this is required, here's another solution:
function orderedShuffle($first, $second) {
$results = [];
$stor = [$first, $second];
$i = mt_rand(0, 1);
// switching between arrays on the fly
while (list(, $v) = each($stor[$i])) {
$results[] = $v;
$i = mt_rand(0, 1);
}
// one array is gone, now we need to add all the elements
// of the other one (as its counter left where it was)
$i = 1 - $i;
while (list(, $v) = each($stor[$i])) {
$results[] = $v;
}
return $results;
}
Demo. The last function is actually quite easy to extend for as many arrays as required.
Can you try this,
<?php
$first = array(1,2,3,4);
$second = array(10,20,30,40);
$arrayMixed=array();
$firstReverse=array_reverse($first);
$secondReverse=array_reverse($second);
$firstReverseCount = count($firstReverse);
$secondReverseCount = count($secondReverse);
foreach($firstReverse as $key=>$val) {
if ($firstReverseCount>0) {
array_push($arrayMixed, array_pop($firstReverse));
if ($secondReverseCount>0) {
array_push($arrayMixed, array_pop($secondReverse));
}
}
}
$ArrayMixeddata = array_merge($arrayMixed, $second);
echo "<pre>";
print_r($ArrayMixeddata);
echo "</pre>";
?>
Not quick ways, but them works.
// with permutations
function combineShuffleOrder($first, $second)
{
// combine into one array with alternation
$firstLen = count($first);
$secondLen = count($second);
$max = max($firstLen, $secondLen);
$result = array();
for($i=0; $i < $max; $i++) {
if ($i < $firstLen)
$result[] = $first[$i];
if ($i < $secondLen)
$result[] = $second[$i];
}
// "shuffle" with permutation
$len = count($result);
for($i=1; $i<$len; $i++) {
if (rand(1, 3) % 2 == 0) {
$tmp = $result[$i-1];
$result[$i-1] = $result[$i];
$result[$i] = $tmp;
$i++; // skip one exchange
}
}
return $result;
}
// with using "shuffle" in subarray
function combineShuffleOrder2($first, $second)
{
// combine into one array with alternation
$firstLen = count($first);
$secondLen = count($second);
$max = max($firstLen, $secondLen);
$result = array();
for($i=0; $i < $max; $i++) {
$sub = array();
if ($i < $firstLen)
$sub[] = $first[$i];
if ($i < $secondLen)
$sub[] = $second[$i];
shuffle($sub);
$result = array_merge($result, $sub);
}
return $result;
}
// with using "shuffle" in subarray if sources arrays are equals by length
function combineShuffleOrder3($first, $second)
{
$max = count($first);
$result = array();
for($i=0; $i < $max; $i++) {
$sub = array(
$first[$i],
$second[$i]
);
shuffle($sub);
$result = array_merge($result, $sub);
}
return $result;
}
$first = array(1,2,3,4);
$second = array(10,20,30,40);
print_r(combineShuffleOrder($first, $second));
print_r(combineShuffleOrder2($first, $second));
print_r(combineShuffleOrder3($first, $second));
I recommend forming a single array of the two input arrays for simpler toggling. Simply loop and consume one element from a randomly selected array and push that selection into the result array. When the pool of arrays is reduced to a single array, kill the loop and append the remaining elements of the last surviving array onto the result array.
I'll use a pool of four arrays (one which is empty from the beginning) to demonstrate that the snippet is robust enough to handle a variable number of arrays, a variable number of elements in each array, and empty arrays.
Code: (Demo)
$first = [1, 2, 3, 4];
$second = [10, 20, 30, 40];
$third = [];
$fourth = ['a', 'b'];
$pool = [$first, $second, $third, $fourth];
$result = [];
while (count($pool) > 1) {
$pullFrom = array_rand($pool);
if (!$pool[$pullFrom]) {
unset($pool[$pullFrom]);
continue;
}
$result[] = array_shift($pool[$pullFrom]);
}
var_export(array_merge($result, ...$pool));
Alternatively without array_merge() and count() calls, but it makes more iterated calls of array_shift(): (Demo)
$pool = [$first, $second, $third, $fourth];
$result = [];
while ($pool) {
$pullFrom = array_rand($pool);
if (!$pool[$pullFrom]) {
unset($pool[$pullFrom]);
continue;
}
$result[] = array_shift($pool[$pullFrom]);
}
var_export($result);
Loop this script until both arrays are done.
$j = 0;
$i = 0;
$r = rand(0, 1);
if($r == 0) {
$ret .= $array1[$i];
$i++;
} elseif($r == 1) {
$ret .= $array2[$j];
$j++;
}
Of course, you have to handle a few exceptions in this code, but it might be the route.
I have this array:
$a = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
Is there a function to convert this to:
$b = array(1, 1, 1, 1, 2, 1, 2, 2);
So basicaly:
$b = array ($a[1]-$a[0], $a[2]-$a[1], $a[3]-$a[2], ... ,$a[n]-$a[n-1]);
Here is the code I have so far:
$a = $c = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
array_shift($c);
$d = array();
foreach ($a as $key => $value){
$d[$key] = $c[$key]-$value;
}
array_pop($d);
There isn't a built-in function that can do this for you, but you could turn your code into one instead. Also, rather than making a second array, $c, you could use a regular for loop to loop through the values:
function cumulate($array = array()) {
// re-index the array for guaranteed-success with the for-loop
$array = array_values($array);
$cumulated = array();
$count = count($array);
if ($count == 1) {
// there is only a single element in the array; no need to loop through it
return $array;
} else {
// iterate through each element (starting with the second) and subtract
// the prior-element's value from the current
for ($i = 1; $i < $count; $i++) {
$cumulated[] = $array[$i] - $array[$i - 1];
}
}
return $cumulated;
}
I think php has not a build in function for this. There are many ways to solve this, but you already wrote the answer:
$len = count($a);
$b = array();
for ($i = 0; $i < $len - 1; $i++) {
$b[] = $a[$i+1] - $a[$i];
}