PHP: Remove the first and last item of the array

前端 未结 7 474
旧巷少年郎
旧巷少年郎 2021-01-31 07:47

Suppose I have this array:

 $array = array(\'10\', \'20\', \'30.30\', \'40\', \'50\');

Questions:

What is the fastest/

相关标签:
7条回答
  • 2021-01-31 08:11

    Removes the first element from the array, and returns it:

    array_shift($array);
    

    Removes the last element from the array, and returns it:

    array_pop($array);
    

    If you dont mind doing them both at the same time, you can use:

    array_shift($array,1,-1));
    

    to knock off the first and last element at the same time.

    Check the array_push, array_pop and array_slice documentation :)

    0 讨论(0)
  • 2021-01-31 08:15
    <?php
    $array  = array("khan","jan","ban","man","le");
    $sizeof_array = sizeof($array);
    $last_itme = $sizeof_array-1;
    //$slicearray= array_slice($array,'-'.$sizeof_array,4);// THIS WILL REMOVE LAST ITME OF ARRAY
    $slicearray = array_slice($array,'-'.$last_itme);//THIS WILL REMOVE FIRST ITEM OF ARRAY
    foreach($slicearray as $key=>$value)
    {
      echo $value;  
      echo "<br>";
    }   
    ?>
    
    0 讨论(0)
  • 2021-01-31 08:16

    array_slice is going to be the fastest since it's a single function call.

    You use it like this: array_slice($input, 1, -1);

    Make sure that the array has at least 2 items in it before doing this, though.

    0 讨论(0)
  • 2021-01-31 08:19
    array_pop($array); // remove the last element
    array_shift($array); // remove the first element
    
    0 讨论(0)
  • 2021-01-31 08:21

    To remove the first element, use array_shift, to remove last element, use array_pop:

    <?php    
    $array = array('10', '20', '30.30', '40', '50');
    array_shift($array);
    array_pop($array);
    
    0 讨论(0)
  • 2021-01-31 08:23

    Check this code:

    $arry = array('10', '20', '30.30', '40', '50');
    $fruit = array_shift($arry);
    $fruit = array_pop($arry);
    print_r($arry);
    
    0 讨论(0)
提交回复
热议问题