We often want to retrieve two or more successive elements from an array. PHP enables you to retrieve a sub section of an array with the array_slice() function, same as the substr() function enables you to extract a section of a string. The function takes three arguments: the array variable to operate on, the index to begin slicing at, and the number to return from the start position.
Below is the running code to retrieve two or more successive elements from an array:
- // define array
- $colors = array(“blue”,“red”,“green”,“black”,“white”,“yellow”,“purple”,“orange”);
- // extract middle 4 elements
- $retrieve_elements = array_slice($colors, 3, 4);
- print_r ($retrieve_elements);
- // results: Array (  => black  => white  => yellow  => purple )