Extracting Contiguous Segments of an Array in PHP

July 20th, 2013 by Laeeq | 1 comment

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:

  1. <?php
  2. // define array
  3. $colors = array(“blue”,“red”,“green”,“black”,“white”,“yellow”,“purple”,“orange”);
  4. // extract middle 4 elements
  5. $retrieve_elements = array_slice($colors, 3, 4);
  6. print_r ($retrieve_elements);
  7. // results: Array ( [0] => black [1] => white [2] => yellow [3] => purple )
  8. ?>

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • How much memory do PHP variables use?
  • Manipulating PHP arrays: push, pop, shift, unshift
  • 10 Super Useful PHP Code Snippets
  • Let’s play with php.ini file Configuration
  • 15+ regular expressions for PHP developers
  •  

     

    1. July 22nd, 2013 at 13:16 | #1

      thanks for the info! will share…

    1. No trackbacks yet.