Parse url querystring into an array


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

This will take an url or just the querystring portion and break it out into an array


Copy this code and paste it in your HTML
  1. /**
  2.   * Parse out url query string into an associative array
  3.   *
  4.   * $qry can be any valid url or just the query string portion.
  5.   * Will return false if no valid querystring found
  6.   *
  7.   * @param $qry String
  8.   * @return Array
  9.   */
  10. function queryToArray($qry)
  11. {
  12. $result = array();
  13. //string must contain at least one = and cannot be in first position
  14. if(strpos($qry,'=')) {
  15.  
  16. if(strpos($qry,'?')!==false) {
  17. $q = parse_url($qry);
  18. $qry = $q['query'];
  19. }
  20. }else {
  21. return false;
  22. }
  23.  
  24. foreach (explode('&', $qry) as $couple) {
  25. list ($key, $val) = explode('=', $couple);
  26. $result[$key] = $val;
  27. }
  28.  
  29. return empty($result) ? false : $result;
  30.  
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.