0
\$\begingroup\$

Example cases:

Need to add x=1, y=2 and querystring variables to the following URLs:

//-- usage
get_link(array('x' => 1, 'y' => 2, 'z' => 'string'));

function get_link( $my_params )
{   
    $param_querystring = "";
    $http_host = $_SERVER['HTTP_HOST'];

    //-- get the part of the url before the querystring, if applicable
    $url = explode( '?', $_SERVER['REQUEST_URI'] );

    $request_uri = $url[0];
    $querystring = $url[1];

    foreach ( $my_params as $param_key => $param_value )
    {
        $param_querystring .= $param_key . '=' . $param_value;
    }

    if ( empty( $querystring ) )
    {
        //-- generates foo.com/blah?x=1&y=2&z=string if no
        //-- querystring was present
        $link = $request_uri . '?' . $param_querystring;
    }
    else
    {

        //-- generates foo.com/blah?a=1&b=2&x=1&y=2&z=string if a=1&b=2 
        //-- querystring was already present.
        $link = $request_uri . $querystring . '&' . $param_querystring;
    }

    return $link;
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You never use $http_host. Besides, your code is broken. Please fix it so we can reopen it (and I can post my answer)! \$\endgroup\$ Commented Jul 11, 2014 at 4:46
  • \$\begingroup\$ Actually, it seems to be a very minor error, so I suppose it's okay for me to post my answer... \$\endgroup\$ Commented Jul 11, 2014 at 5:03

2 Answers 2

6
\$\begingroup\$
  • Your code is very spaced out. It doesn't need to be.
  • Consider using industry-standard style by using Egyptian braces for control structures like if and foreach.
  • Get rid of the $http_host variable; you never use it.
  • Consider generalising your function to accept any URL instead of pulling REQUEST_URI.
  • You're kind of reinventing the wheel; PHP has the built-in functions parse_str and http_build_query that you can use.
  • Do you intend to replace existing variables, or just to append them to the request?

Here's an example that takes advantage of the built-in functions, and intelligently merges in conflicts. (ideone)

/**
 *  Like array_merge, but will recursively merge array values.
 *
 *  @param array $a1
 *      The array to be merged into.
 *  @param array $a2
 *      The array to merge in. Overwrites $a1, when string keys conflict.
 *      Numeric keys will just be appended.
 *  @return array
 *      The array, post-merge.
 */
function merge_query_var_arrays($a1, $a2) {
    foreach ($a2 as $k2 => $v2)
        if (is_string($k2))
            $a1[$k2] = isset($a1[$k2]) && is_array($v2) ? merge_query_var_arrays($a1[$k2], $v2) : $v2;
        else
            $a1[] = $v2;
    return $a1;
}

/**
 *  @param string $query_string
 *      The URL or query string to add to.
 *  @param string|array $vars_to_add
 *      Either a string in var=val&[...] format, or an array.
 *  @return string
 *      The new query string. Duplicate vars are overwritten.
 */
function add_query_vars($query_string, $vars_to_add) {
    if (is_string($vars_to_add))
        parse_str($vars_to_add, $vars_to_add);
    if (preg_match('/.*\?/', $query_string, $match))
        $query_string = preg_replace('/.*\?/', '', $query_string);
    parse_str($query_string, $query_vars);

    $query_vars = merge_query_var_arrays($query_vars, $vars_to_add);
    return @$match[0] . http_build_query($query_vars);
}
\$\endgroup\$
2
\$\begingroup\$

I use this function in my pagination script to append query strings to the ?p= (page number) query, this enables me to sort a table from the same page or set the Limit in a table populated by MySQL

    public function modQuery($add_to, $rem_from = array(), $clear_all = false){
        if ($clear_all){
            $query_string = array();
        }else{
            parse_str($_SERVER['QUERY_STRING'], $query_string);
        }
        if (!is_array($add_to)){ $add_to = array(); }
            $query_string = array_merge($query_string, $add_to);
        if (!is_array($rem_from)){ $rem_from = array($rem_from); }
            foreach($rem_from as $key){
        unset($query_string[$key]);
        }
    return http_build_query($query_string);
    }

Usage:

You can use it in a href:

'<a href="?'.modQuery(array('query'=>'queryValue','query'=>'queryValue'))).'">Some Query</a>'
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.