0

I am creating a function to set query vars as below.

function set_query_var(array $params)
{
    $count = count($params);
    $query_var = '?';        

    foreach ( $params as $key => $value)
    {
        $query_var .= $key . '=' . $value .
        (($count > 1) ? '&' : NULL);
    }

    return $query_var;
}

Above function works fine but only issue is that, it is adding & to the end loop which I don't want.

How can I fix it?

2
  • 5
    Looks like you're reinventing the wheel: http_build_query() Commented Aug 12, 2014 at 7:05
  • @AlmaDo +1 and thanks a lot. I didn't know this function. It might be useful here to me.. Thanks again. Commented Aug 12, 2014 at 7:10

3 Answers 3

7

I always use implode and array:

function set_query_var(array $params)
{
    $query_var = [];        

    foreach ($params as $key => $value) {
        $query_var[] = "{$key}={$value}";
    }

    return '?' . implode('&', $query_var);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wonderful and optimized solution. Thanks a lot.... BTW Alma Do also gave me nice suggestion to use built in function.
@CodeLover yes, but my way is used more widely, not just for URL. I usually use it for SQL WHERE statements.
0
function set_query_var(array $params)
{
    $count = count($params);
    $query_var = '?';        

    foreach ( $params as $key => $value)
    {
        $query_var .= $key . '=' . $value .
        (($count > 1) ? '&' : NULL);
    }
    $query_var = rtrim( $query_var, "&");
    return $query_var;
}

Comments

0

An easy and dirty solution to you problem is to remove the last & from your string.

rtrim($string, "&");

would cut trailing &.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.