Home > other >  PHP - get a sub array skipping 2-3 elements from end
PHP - get a sub array skipping 2-3 elements from end

Time:05-08

Is there any efficient way to get a sub-array by skipping every 2/3 elements and starting from the end (maintain last element if sub array amount is not divisable by x). Basically i have a large array of 300k elements that i want to turn to 100k or 150k.

$array = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

$x = 1;

$new_array = array(1,3,5,7,9,11,13,15);

$x = 2;

$new_array = array(0,3,6,9,12,15);

$x = 3;

$new_array = array(3,7,11,15);

CodePudding user response:

function skip_x_elements($array, $x)
{
    $newArray = [];
    $skipCount = 0;
    foreach ($array as $value) {
        if ($skipCount === $x) {
            $newArray[] = $value;
            $skipCount = 0;
        } else {
            $skipCount  ;
        }
    }
    return $newArray;
}

This should do what you want.

CodePudding user response:

Improving upon @Dieter_Reinert answer, so you can also retain the keys inside said array, here is a slightly more flexible version:

function return_every_x($array, $x, $start_with_first = false){
        
    # the line below allows every $x'th value to be grabbed;
    # you can remove it if you want $x amount of values to be skipped.
    # essentially if you want, for example, every 5th to be grabbed, you are skipping 
    # every 4. So this makes it a bit easier to use; but it can be removed if preferred
    $x = $x - 1;
    
    # gives option to start with the first value of array (example shown in second array output)
    $count = ($start_with_first) ? $x:0;
    
    # start temp array to return later
    $temparr = [];
    
    # start looping through array
    foreach($array as $key => $value){
        
        # if the counter equals $x
        if($count === $x){
            
            # input the key => value into our temp array & reset the counter
            $temparr[$key] = $value;
            $count = 0;
            
        # if not, increase counter by 1.
        }else $count  ;
    }
    
    # return our temp array after the loop is complete
    return $temparr;
}

Online PHP Sandbox Demo: https://onlinephp.io/c/b66ff

  • Related