简体   繁体   中英

How to remove every third element in a php array until only one element remains and print that element?

The array is like this

$a = array(1,2,3,4,5,6,7,8);

After that in each iteration the 3rd element should be removed until it reaches to a single element

the iteration will be something like this

index:0 1 2 3 4 5 6 7

value:1 2 3 4 5 6 7 8
this is the normal one

index:0 1 2 3 4 5 6 7

value:1 2 4 5 7 8
here 3 and 6 removed as they came out as the 3rd elements

then after 6 is removed it should count 7 and 8 as 1st and 2nd and go to value 1 which makes 1 as the 3rd element.This continues until there is only one element remaining.

output

12345678

1245678

124578

24578

2478

478

47

7

7 is the remaining element

Your looking for array_chunk()

$a = array(1,2,3,4,5,6,7,8);
$thirds = array_chunk($a, 3);

$thirds now is like:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
        )   
)

Then just loop through the $thirds array and array_pop() to grab the last value.

However, I'm not sure why you're looking to get 7 at the end and not 8. Can you explain?

here is the code, hope it helps.

<?php
$array = [1,2, 3,4,5,6,7,8];

function removeAtNth($array, $nth)
{
    $step = $nth - 1;       //gaps between operations
    $benchmark = 0;    
    while(isset($array[1]))
    {   
        $benchmark += $step;
        $benchmark = $benchmark > count($array) -1 ? $benchmark % count($array) : $benchmark;
        echo $benchmark."\n";
        unset($array[$benchmark]);
        $array = array_values($array);
        echo implode('', $array)."\n";
    }   
}

removeAtNth($array, 3); 

result:

kris-roofe@krisroofe-Rev-station:~$ php test.php
1245678
124578
24578
2478
478
47
7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM