2

I am using array_splice to remove 0th and 1st index of an array and I want to remove last index too.

How to do it?

array_splice($arr, 0, 2);

Here is my array -

Array ( [code] => 1 [name] => Abc [On] => 15619 [OP] => 15886 [Vac] => 31505 [Target] => 50702 [Co] => 62.14 )
4
  • 1
    array_splice($arr, (count($arr)-1), 1); Commented Feb 22, 2017 at 12:39
  • 4
    Tip: array_slice(array_values($arr), 2, count($arr)-3); Commented Feb 22, 2017 at 12:40
  • @JustOnUnderMillions add this as a solution. it's perfect Commented Feb 22, 2017 at 12:49
  • @JustOnUnderMillions - you can also use a negative offset (-1) for the 3rd argument, rather than count-3 Commented Feb 22, 2017 at 13:02

7 Answers 7

2

array_splice with proper syntax can extract the array you want.

$arr = [1,2,3,4,5];
$newArr = array_splice($arr, 2, -1);
print_r($newArr);
// prints
Array
(
    [0] => 3
    [1] => 4
)
Sign up to request clarification or add additional context in comments.

Comments

2

please try this

     $a1 = Array ( 
           'code' => 1,
           'name' => Abc, 
           'On' => 15619, 
           'OP' => 15886, 
           'Vac' => 31505, 
           'Target' => 50702, 
           'Co' => 62.14 );
       echo "<pre>"; 
       print_r(array_splice($a1,2,-1));

Output will be

Array
(
    [On] => 15619
    [OP] => 15886
    [Vac] => 31505
    [Target] => 50702
)

Comments

2

You can do it in this simple way:

$arr = array_slice($arr, 2, count($arr)-3, true);

  • offset 2 for skipping the first 2 entries
  • -3 because second arg is for length not second offset or range

2 Comments

$arr = array_slice($arr, 2, -1, true);
@Mark Baker OK, thnx
2

Just use two shift and one pop operations on the main array.

$array = your_array();

array_shift($array); //remove 1st
array_shift($array); //remove 2nd
array_pop($array); //remove last

print_r($array); //required array

Comments

1

Here is the easiest solution I have got.

array_pop

(PHP 4, PHP 5, PHP 7) array_pop — Pop the element off the end of array

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

Source : php.net/manual/en/function.array-pop.php

1 Comment

This is answer is simply wrong. How does it have two upvotes?!?
1

You can use more shorter syntax of unset() as

unset($arr[1], $arr[2], count($arr) );

2 Comments

FATAL ERROR Can't use function return value in write context
Plz check your answer, keep assoc keys in mind and the use of count here and that the first entry of an index is 0 not 1 in php
0

You have two options while using splice function

First is:

array_splice($arr, 0, 2);
array_splice($arr, -1);
print_r($arr);

Second option is use splice function in smart way

$arr1 = array_splice($arr, 2, -1);
print_r($arr1);

Hope it will help you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.