Removing successive duplicate occurrences in an array - php

Is there any way that I can remove the successive duplicates from the array below while only keeping the first one?
The array is shown below:
$a=array("1"=>"go","2"=>"stop","3"=>"stop","4"=>"stop","5"=>"stop","6"=>"go","7"=>"go","8"=>"stop");
What I want is to have an array that contains:
$a=array("1"=>"go","2"=>"stop","3"=>"go","7"=>"stop");

Successive duplicates? I don't know about native functions, but this one works. Well almost. Think I understood it wrong. In my function the 7 => "go" is a duplicate of 6 => "go", and 8 => "stop" is the new value...?
function filterSuccessiveDuplicates($array)
{
$result = array();
$lastValue = null;
foreach ($array as $key => $value) {
// Only add non-duplicate successive values
if ($value !== $lastValue) {
$result[$key] = $value;
}
$lastValue = $value;
}
return $result;
}

You can just do something like:
if(current($a) !== $new_val)
$a[] = $new_val;
Assuming you're not manipulating that array in between you can use current() it's more efficient than counting it each time to check the value at count($a)-1

Related

How to keep only empty elements in array in php?

I have one array and i want to keep only blank values in array in php so how can i achieve that ?
My array is like
$array = array(0=>5,1=>6,2=>7,3=>'',4=>'');
so in result array
$array = array(3=>'',4=>'');
I want like this with existing keys.
You can use array_filter.
function isBlank($arrayValue): bool
{
return '' === $arrayValue;
}
$array = array(0 => 5, 1 => 6, 2 => 7, 3 => '', 4 => '');
var_dump(array_filter($array, 'isBlank'));
use for each loop like this
foreach($array as $x=>$value)
if($value=="")
{
$save=array($x=>$value)
}
if you want print then use print_r in loop
there is likely a fancy built in function but I would:
foreach($arry as $k=>$v){
if($v != ''){
unset($arry[$k]);
}
}
the problem is; you are not using an associative array so I am pretty sure the resulting values would be (from your example) $array = array(0=>'',1=>''); so you would need to:
$newArry = array();
foreach($arry as $k=>$v){
if($v == ''){
$newArry[$k] = $v;
}
}

Replace duplicate words in array (not remove)

I have an array that have multiple set of words, some of them might be duplicated, and i want to replace the duplicated words from array with word: duplicate, and also keep one original.
So if i have 5 duplicates, i want 4 of them to be replaced with duplicate and keep original one
$my_array = (0=>'test', 1=>'test2',2=>'test3',3=>'test');
As you see in my array, the array keys 0 and 3 has same value, i want to replace the last value with word 'duplicate'
$my_array = (0=>'test', 1=>'test2',2=>'test3',3=>'duplicate');
I tried different methods but without success:(
Here's one way to do it:
<?php
$my_array = array(0=>'a', 1=>'a',2=>'b',3=>'c');
print_r($my_array);
$my_array2 = array_unique($my_array);
foreach($my_array as $key => $value) {
if (!array_key_exists($key, $my_array2)) {
$my_array[$key] = 'duplicate';
}
}
print_r($my_array);
Try this, just remember what values you have visited.
$visited = array();
foreach($my_array as $key=>$val) {
if(isset($visited[$val])) {
$my_array[$key] = 'duplicate';
} else {
$visited[$val] = true;
}
}

PHP Find last key of associative multidimensional array

This is what I have tried:
foreach ($multiarr as $arr) {
foreach ($arr as $key=>$val) {
if (next($arr) === false) {
//work on last key
} else {
//work
}
}
}
After taking another look, I thinknext is being used wrong here, but I am not sure what to do about it.
Is it possible to see if I'm on the last iteration of this array?
$lastkey = array_pop(array_keys($arr));
$lastvalue = $arr[$lastkey];
If you want to use it in a loop, just compare $lastkey to $key
You will need to keep a count of iterations and check it against the length of the array you are iterating over. The default Iterator implementation in PHP does not allow you to check whether the next element is valid -- next has a void return and the api only exposes a method to check whether the current position is valid. See here http://php.net/manual/en/class.iterator.php. To implement the functionality you are thinking about you would have to implement your own iterator with a peek() or nextIsValid() method.
Try this:
foreach ($multiarr as $arr) {
$cnt=count($arr);
foreach ($arr as $key=>$val) {
if (!--$cnt) {
//work on last key
} else {
//work
}
}
}
See below url i think it help full to you:-
How to get last key in an array?
How to get last key in an array?
Update:
<?php
$array = array(
array(
'first' => 123,
'second' => 456,
'last' => 789),
array(
'first' => 123,
'second' => 456,
'last_one' => 789),
);
foreach ($array as $arr) {
end($arr); // move the internal pointer to the end of the array
$key = key($arr); // fetches the key of the element pointed to by the internal pointer
var_dump($key);
}
output:
string(4) "last" string(4) "last_one"
This function (in theory, I haven't tested it) will return the last and deepest key in a multidemnsional associative array. Give I a run, I think you'll like it.
function recursiveEndOfArrayFinder($multiarr){
$listofkeys = array_keys($multiarr);
$lastkey = end($listofkeys);
if(is_array($multiarr[$lastkey])){
recursiveEndOfArrayFinder($multiarr[$lastkey]);
}else{
return $lastkey;
}
}

Foreaching an array and matching?

How would I iterate through an array (300+ items, imported via simplexml) and pull out every item that has a certain $x->channel->item->title and put that into a different array?
I can't make heads or tails of the haystack needle thing or how to push arrays
Say I have an array (needle) like: array("3332","3300","3493","8380") and I want to match if any of those appear through the big array (haystack). How do I do this?
You have to iterate over your big array, and check for the value of $x->channel->item->title. If it meets your criteria, push it into the new array:
$theArray; // Your 300+ array
$lookFor = array('firstthing', 'second thing', 'third thing');
$newArray = array();
foreach($theArray as $x) {
if ( in_array($x->channel->item->title, $lookFor) ) {
array_push($newArray, $x);
}
}
foreach($yourArray as $key => $value)
{
//do your things with $key and/or $value
}
Modifying from Joseph's loop, you can do:
$theArray; // Your 300+ array
$newArray = array();
$matchArray = array("3332","3300","3493","8380");
foreach($theArray as $x) {
if (in_array($x->channel->item->title, $matchArray)) {
array_push($newArray, $x);
}
}
Check out in_array() at http://php.net/manual/en/function.in-array.php

search through array and find 1 couple optimally?

Let`s suppose we have a simple (non-assoc) array with 100001 values and these values set in unsorted order like 45, 12, 32, 23. We know that in this array is 1 couple of numbers, how to find it optimally - not via 2 foreach loops and even not via 2 for loops with 100001/2 division?
Use array_count_values:
$result=array_count_values($arr);
$value=array_search(2, $result);
print $value;
Since your array is not sorted, the ONLY search method other than random scatteryshot is to scan the array sequentially and look for your two numbers:
$first_key = null;
$second_key = null;
foreach($array as $key => $val) {
if ($val == $first_number) {
$first_key = $key;
}
if ($val == $second_number) {
$second_key = $key;
}
if (!is_null($first_key) && !is_null($second_key)) {
break;
}
}
Once both numbers are found, or you reach the end of the array, the loop will exit.

Categories