Our blog

 

PHP Arrays Maintain Index After Removing Exsisting

One of the features that makes PHP such a powerful language is it's arrays. They allow for really complex data structures to be stored and worked on really easy. One interesting aspect of them is that they maintain there index if emptied one element at a time.

Taken from php.net: http://php.net/manual/en/language.types.array.php

PHP:
  1. <?php
  2. // Create a simple array.
  3. $array = array(1, 2, 3, 4, 5);
  4. print_r($array);
  5.  
  6. // Now delete every item, but leave the array itself intact:
  7. foreach ($array as $i => $value) {
  8.     unset($array[$i]);
  9. }
  10. print_r($array);
  11.  
  12. // Append an item (note that the new key is 5, instead of 0).
  13. $array[] = 6;
  14. print_r($array);
  15.  
  16. // Re-index:
  17. $array = array_values($array);
  18. $array[] = 7;
  19. print_r($array);
  20. ?>

Will output:

CODE:
  1. Array
  2. (
  3.     [0] => 1
  4.     [1] => 2
  5.     [2] => 3
  6.     [3] => 4
  7.     [4] => 5
  8. )
  9. Array
  10. (
  11. )
  12. Array
  13. (
  14.     [5] => 6
  15. )
  16. Array
  17. (
  18.     [0] => 6
  19.     [1] => 7
  20. )

More Reading:

 

Leave a Reply