I have an array:
$arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
Is there a way to make it contain elements only divisible by 3 (or n)? So in the above example g
would be removed as it's left over from a division of 3?
EDIT
I want amount of elements divisible by 3.
You can use a combination of array_slice()
, count()
and modulus (%
) to get the array evenly divisible:
$arr_length = count($arr);
$new_arr = array_slice($arr, 0, $arr_length - ($arr_length % 3));
@panthro simply try with for loop like below and use array_pop()
<?php
$arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
if(count($arr) % 3 != 0){
$remainder = count($arr) % 3;
for($i=0;$i < $remainder;$i++){
array_pop($arr);
}
}
echo "<pre>";
print_r($arr); //final array divisible by 3
Sounds like you want the length to be divisible by 3 and you want to remove elements until that happens. array_slice
can help you out here.
$to_remove = count($arr) % 3;
if($to_remove > 0){
$arr = array_slice($arr, 0, -$to_remove);
}