1

I am trying to add params to a url but "&" is appearing twice.

it shows: "/getAllBrands?&key1=2&key2=1&limit=1"

I want it to be like this: "/getAllBrands?key1=2&limit=1"

url = sprintf("/%s?", $apiMethod);
$pos = strpos($url, "?");
foreach ($params[0] as $key => $value) {

    if ($pos) {
        $url .= "&";
    }
    $url .= sprintf('%s=%s', $key, urlencode($value));
}

Would appreciate if someone could help, thank you.

3
  • 5
    just simply use http_build_query and save yourself with that hibbyjibby string manipulation Commented Feb 13, 2019 at 7:34
  • 1
    PHP has a great function available to build HTTP parameters called http_build_query Commented Feb 13, 2019 at 7:34
  • 1
    @Ghost I was gonna say the same thing! lol Commented Feb 13, 2019 at 7:35

1 Answer 1

1

How about just doing this:

 $url .= http_build_query($params);

or

 $url .= http_build_query($params[0]);

Not sure exactly how $params is... but you should get the point.

Here's the docs: http://php.net/manual/en/function.http-build-query.php

Sign up to request clarification or add additional context in comments.

1 Comment

Worked fine, thanks v much. Used the second option :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.