Jump to content

Count duplicate adjacent (Array)


BeHappy
Go to solution Solved by Barand,

Recommended Posts

Hello;

I would like to do the following operation;

Count duplicate (adjacent)

my code

 

        <?php  
      
$Array = array("test", "test", "hello", "test", "world", "world", "world", "hello", "test");


 for( $i= 0 ;  $i <= 6 ;$i++ ) {
$j=1;
 if ($Array[$i] === $Array[$i+1]) {
 
 $j+=$j; 

echo  $j;
}
?>

and showing something like 2,1,1,3,1,1

Thanks

Link to comment
Share on other sites

15 minutes ago, Barand said:

if array == array[i-1]

then you have adjacent duplicates

Thank you Barand;

This my array

$Array = array("test", "test", "hello", "test", "world", "world", "world", "hello", "test");

Well, i would like to show a list with adjacent duplicates for example the word  test 2 not 4 duplicates

and finally the output will be like this 2,1,1,3,1,1 

the problem that array_count_values show the all duplicates, i would like to show the adjacent duplicates

Edited by BeHappy
Link to comment
Share on other sites

11 minutes ago, Barand said:

You've had some clues. What have you tried?

I have created this code but i think there's a problem with it

<?php   
$array = array("test", "test", "hello", "test", "world", "world", "world", "hello", "test");
             
$j=1;
for( $i= 0 ;  $i <= 7 ;$i++ ){ 
                 if ($array[$i] === $array[$i+1])
                 
	{ 
echo $j .= $j+1;
	}
	
	else
	{
      echo "1";
    }
       
}?>

output = 1211112131213121411

not 2,1,1,3,1,1  😅

Edited by BeHappy
Link to comment
Share on other sites

  • Solution

try

$arr = array("test", "test", "hello", "test", "world", "world", "world", "hello", "test");

$prev = '';
$results = [];
$j = 0;
foreach ($arr as $i => $v) {
    if ($v != $prev) {
        $j = $i;
        $results[$j] = 1;
        $prev = $v;
    }
    else {
        $results[$j]++;
    }
}

foreach ($results as $k => $v) {
    echo "$arr[$k] : $v <br>";
}

Result:

test : 2 
hello : 1 
test : 1 
world : 3 
hello : 1 
test : 1 

 

  • Great Answer 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.