How to extract all values ​​from an array except the last two in php

Hello everyone.
How to extract all values ​​(any number) from an array except the last two or three in php?
Thanks in advance!


Answer 1, authority 100%

For regular arrays

$arr=explode(" ", "1 2 3 4 5 6 7 8 9 0");
var_dump(array_slice($arr, 0, sizeof($arr)-2));

For associative arrays

$arr=array("a"=>12, "b"=>13, "c"=>14, "d"=>15);
var_dump(array_slice($arr, 0, sizeof($arr)-2, true));

Answer 2, authority 40%

function get_all_exept($num,$arr,$begin=false){
  for($i=0;$i<$num,count($arr);$i++){//      num 
    if($begin){//     
      array_shift($arr);
    }else{
      array_pop($arr);
    }
  }
  return $arr;
}

Works even for associative arrays.
If an array with numeric keys arranged sequentially from 0, then everything is even simpler: we take it out in a loop.

for($i=num;$i<count($arr);$i++)

for all but the first three

for($i=0;$i<(count($arr))-$num;$i++)

for all but the last three


Answer 3

In what sense to extract? If you meant to extract to another array, then you can do this:

<?php
    $a = array(1, 2, 3, 4, 5, 6, 7);
    $b = array();
    if (count($a) >= 2) {
        for ($i = 0; $i < count($a) - 2; $i++) {
            $b[$i] = $a[$i];
        }    
    } else {
        echo "    !";
    }
    var_dump($a, $b);
    ?>

Answer 4

I think something like this…

<?php
$arr[] = 1; //  
$arr[] = 3; //  
$arr[] = 5; //  
$result = count($arr)-2; //        
// $result == 3 
echo $result; //    1
?>