How to slice an array with array_slice() function in PHP

6 Answers

0 votes
$arr = array(1, 2, 3, 4, 5, 6, 7);
$arr1 = array_slice($arr, 1, 3);
echo "arr:<br />";
print_r($arr); 
echo "<br />arr1:<br />";
print_r($arr1); 
 
 
/*
run:

arr:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
arr1:
Array ( [0] => 2 [1] => 3 [2] => 4 )  
   
*/


answered Apr 21, 2014 by avibootz
edited Mar 8, 2016 by avibootz
0 votes
$arr = array("a", "b", "c", "d", "e", "f");
$arr1 = array_slice($arr, 2, 2);
echo "arr1:<br />";
print_r($arr1); 

 
/*
run:

arr1:
Array ( [0] => c [1] => d )  
   
*/

 



answered Mar 8, 2016 by avibootz
0 votes
$arr = array("a", "b", "c", "d", "e", "f");
$arr1 = array_slice($arr, 2, 1);
echo "arr1:<br />";
print_r($arr1); 

 
/*
run:

arr1:
Array ( [0] => c ) 
   
*/

 



answered Mar 8, 2016 by avibootz
0 votes
$arr = array("a", "b", "c", "d", "e", "f");
$arr1 = array_slice($arr, 2, -1); // offset is negative - start from the end of the array
echo "arr1:<br />";
print_r($arr1); 

 
/*
run:

arr1:
Array ( [0] => c [1] => d [2] => e ) 
   
*/

 



answered Mar 8, 2016 by avibootz
0 votes
$arr = array("a", "b", "c", "d", "e", "f");
$arr1 = array_slice($arr, 2, -2); // offset is negative - start from the end of the array
echo "arr1:<br />";
print_r($arr1); 

 
/*
run:

arr1:
Array ( [0] => c [1] => d ) 
   
*/

 



answered Mar 8, 2016 by avibootz
0 votes
$arr = array("a", "b", "c", "d", "e", "f");
$arr1 = array_slice($arr, 2, -1, true); // offset is negative - start from the end of the array
echo "arr1:<br />";
print_r($arr1); 

// true - preserve the keys 
 
/*
run:

arr1:
Array ( [2] => c [3] => d [4] => e ) 
   
*/

 



answered Mar 8, 2016 by avibootz
...