PHP Array, remove only duplicates next to eachother - php

$arr = array(1, 2, '...', '...', '...', 6, 7, 8, '...', 10);
array_unique creates: array(1, 2, '...', 6, 7, 8, 10);
I want the following: array(1, 2, '...', 6, 7, 8, '...', 10);
So basically, I'm looking for a fast way to remove only duplicates next to eachother.

$result = array();
$first = true;
foreach ($array as $x) {
if ($first || $x !== $previous) $result[] = $x;
$previous = $x;
$first = false;
}
Alter the $x !== $previous condition to suit your preferred definition of "duplicate". For example, array_unique does a loosely-typed comparison.

I would do it this way:
<?php
$arr = array(1, 2, '...', '...', '...', 6, 7, 8, '...', 10);
$el = $arr[0];
$out = $arr;
for ($i=1, $c = count($out); $i<$c; ++$i) {
if ($arr[$i] == $el) {
unset($out[$i]);
}
else {
$el = $out[$i];
}
}
$out = array_values($out);
foreach ($out as $i) {
echo $i."<br />";
}
Output:
1
2
...
6
7
8
...
10

Related

Store PHP array to csv in Column wise

$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)
)

Php ad every 6th item except first row

I need to add an item every 6th position.
So it would look like this:
[
//item1
//item2
//item3
//item4
//item5
//NEW ITEM HERE
//item7
//item8
//item9
//item10
//item11
//NEW ITEM
]
I already tried this:
foreach($ports as $key => $port)
{
if($key %9 == 2) {
$ports->splice($key, 0, [$ads]);
}
}
But that's not working any idea?
Use array_chunk and add element to each of sub-arrays:
$portsChunks = array_chunk($ports, 5); // Split array to sub-arrays of max-5 elements.
// Add new element if chunk is full length.
// Means last one will not receive new element if it's shorter than 5
array_walk($portsChunks, function (&$array) {
if (count($array) == 5) {
$array[] = 'New Item';
}
});
// Use arguments unpacking to pass all chunks to array_merge
$ports = array_merge(...$portsChunk);
Example
You can use foreach loop:
$ports = range(1,50);
$new_ports = [];
foreach ($ports as $key => $port) {
$new_ports[] = $port;
if(!(($key+1)%5))
$new_ports[] = 'New item';
}
print_r($new_ports);
$ports = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6];
$ports = array_chunk($ports, 5);
foreach ($ports as &$port){
array_push($port, 'new value');
}
unset($port);
if(count($ports[count($ports)-1]) < 6){
array_pop($ports[count($ports)-1]);
}
$ports = array_merge(...$ports);
you just need a new array to hold all of your data. and then you iterate over your old array and after each 5th position insert a new element. something like this
$result = [];
$ports = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$porstCount = count($ports);
for ($i = 0; $i < $portsCount; $i++) {
$result[] = $ports[$i];
if ($i > 0 && $i % 5 === 0) {
$result[] = 'new element';
}
}
// $result will be [1, 2, 3, 4, 5, 'new element', 6, 7, 8, 9, 10, 'new element', 11, 12]
I hope below case solves your problem:
$newarr = array();
$cnt = 1;
foreach($arr as $key=>$value){
$newarr[] = $value;
if($cnt%5 == 0){
$newarr[] = 'this is new item';
}
$cnt++;
}
print_r($newarr);

best way to count the bigger elements on the right and left side of an array

For example, in php
$arr = [9, 4, 3, 5, 2, 6];
then,
$output = [[0,0], [1,2], [2,2], [1,1], [4,1], [1,0]];
[0, 0] = the bigger elements of 9 is 0 on both side
[1, 2] = the bigger elements of 4 is 1 (9) on left and 2 (5, 6) on right side ... [ 9 > 4] - [ 5 > 4, 6 > 4 ]
[2, 2] = the bigger elements of 3 is 2 (9, 4) on the left and 2 (5, 6) on right side
[1, 1] = the bigger elements of 5 is 1 (9) on the left and 1 (6) on the right side
[4, 1] = the bigger elements of 2 (9, 4, 3, 5) is 4 on the left and 1 (6) on the right side
[1, 0] = the bigger elements of 6 is 1 (9) on the left and 0 (no elements after 6) on the right side
I want it in O(n log(n)), is it possible?
Looks like lots of answers already, you could do this with some of the array functions like some of the answers did, but since this is probably for your homework best to keep it simple. I keep track of whether it's left or right that should be incremented each iteration by using the $side variable.
$arr = [9, 4, 3, 5, 2, 6];
$results = [];
for ($x = 0; $x < count($arr); $x++) {
$results[$x] = [0,0];
$side = 0;
for ($y = 0; $y < count($arr); $y++) {
if ($arr[$y] > $arr[$x]) {
$results[$x][$side]++;
} elseif ($arr[$x] == $arr[$y]) {
$side = 1;
}
}
}
You need to loop through $arr to get each value, and then, in the loop, loop again through $arr to get the other values. Then, in the second loop, you build your output array by comparing both the value (to know if the number is, indeed, bigger) and the key (to know if it's on the left or the right).
$arr = array(9, 4, 3, 5, 2, 6);
$output = array();
foreach ($arr as $key=>$value) {
$out = array(0, 0);
foreach ($arr as $key2=>$value2) {
if ($key2 == $key) # If it's the same element
continue;
if ($value2 > $value) {
if ($key2 < $key)
$out[0]++;
else
$out[1]++;
}
}
$output[] = $out;
}
print_r($output);
See the output here.
Try this:
function fix_array($array) {
$return_array = array();
foreach ($array as $i => $value){
$left = array_slice($array, 0, $i);
$count_left = count(array_filter($left, function($var) use($value){
return $var > $value;
}));
$right = array_slice($array, $i + 1);
$count_right = count(array_filter($right, function($var) use($value){
return $var > $value;
}));
$return_array[] = [$count_left, $count_right];
}
return $return_array;
}
$arr = [9, 4, 3, 5, 2, 6];
$new_array = fix_array($arr);
print_r($new_array);
Simply compare it with left and right values. Try this:
$arr = [9, 4, 3, 5, 2, 6];
$total = count($arr);
$new_arr=array();
foreach ($arr as $key => $value) {
$left = 0;
$right = 0;
for ($i=0; $i < $total; $i++) {
if($key > $i && $arr[$i] > $arr[$key])
{
$left++;
}
elseif ($key < $i && $arr[$i] > $arr[$key]) {
$right++;
}
}
$new_arr[]=[$left,$right];
}
echo "<pre>";
print_r($new_arr);
Try the following code using array_walk()
<?php
$arr = [9, 4, 3, 5, 2, 6];
$finalArray =[];
array_walk($arr, function($value,$key) use(&$finalArray,&$arr) {
$param ['pre_val']=0;
$param ['post_val']=0;
$param ['current_index'] = $key;
$param ['current_value'] = $value;
$arr2 = $arr;
array_walk($arr2, function(&$value,$key) use(&$finalArray,&$param) {
if($key < $param['current_index']){
if($value > $param['current_value']){$param['pre_val'] ++;}
}else{
if($value > $param['current_value']){$param['post_val'] ++;}
}
$finalArray[$param['current_index']][0] = $param['pre_val'];
$finalArray[$param['current_index']][1] = $param['post_val'];
});
});
print_r($finalArray);

Remove duplicates of array

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.

Cumulative array

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];
}

Categories