Hello.
How to extract from the array all the values (any number), except for the last two or three in php?
Thank you in advance!
4 answers
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));
- ugh you =) Completely out of my head. - knes
|
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 in series from 0, then everything is still simpler: remove it by 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
|
In what sense to extract? If it meant to extract to another array, then you can:
<?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); ?>
|
I think something like this ...
<?php $arr[] = 1; // элемент массива $arr[] = 3; // элемент массива $arr[] = 5; // элемент массива $result = count($arr)-2; // длинна всего массива за минусом двух последних элементов // $result == 3 echo $result; // на экран получим 1 ?>
- I would not like to say the obvious things, but instead of the first three lines you can write
$arr = [1, 3 ,5];
- Alex Belyaev
|