A utility function to preserve an array in a session.


/ Published in: PHP
Save to your folder(s)

A utility function to preserve an array in a session. Adding the newest element to the beginning of the array and popping out the last one. Useful for displaying for instance; your last searches option in your website.


Copy this code and paste it in your HTML
  1. // FUNCTION : array_stack_session
  2. // RETURNS : the manipulated session array
  3. // USAGE:
  4.  
  5. <?php
  6.  
  7. $_SESSION['last_searches'] = array_stack_session("newItem", $_SESSION['last_searches']);
  8.  
  9. ?>
  10.  
  11. function array_stack_session( $element, $array_session, $limit = 5 ) {
  12.  
  13. if ( !(is_array($array_session)) ) {
  14. $array_session = array();
  15. }
  16.  
  17. array_unshift($array_session, $element);
  18.  
  19. if ( sizeof($array_session)>$limit ) {
  20. array_pop($array_session);
  21. }
  22.  
  23. return $array_session;
  24.  
  25. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.