3

The PHP function http_build_query is quite handy for building an URL with GET parameters. But sometimes I like to use value-less "boolean" parameters, like so:

/mypage?subscription-id=42&cancel-renewal

Which I then check with a simple isset. Can I achieve this result with http_build_query?

EDIT: Assigning empty values to the parameter does not seem to work :

  • cancel-renewal => '' results in cancel-renewal=
  • cancel-renewal => null results in the parameter being omitted
  • cancel-renewal => false results in cancel-renewal=0
9
  • http_build_query save data in variables in the form of associative array and then pass that as a parameters. While in get request you need to write a parameters in url. You may assign the empty value to that key. Commented Mar 21, 2019 at 14:47
  • I guess by doing $query['cancel-renewal'] = "";. I'm not sure.. Commented Mar 21, 2019 at 14:48
  • @AaronJonk That results in cancel-renewal= Commented Mar 21, 2019 at 14:49
  • 2
    Why does that matter, it's never seen anywhere. cancel-renewal is the same as cancel-renewal= Commented Mar 21, 2019 at 15:08
  • 1
    You'll have to write your own replacement function, I don't think there's any way to make the built-in function do what you want. Commented Mar 21, 2019 at 15:12

2 Answers 2

3

Can I achieve this result with http_build_query?

No. Internally http_build_query appends the = key-value separator no matter what is the value of the parameter. You can see the source code here (PHP 7.3.3)

Means you either need to accept the cancel-renewal= look of the parameter or may be redesign the path to have something like /mypage/cancel-renewal?subscription-id=42

Third option would be to write your own simple function to build the query string.

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

Comments

0

Use this;

$query = array("subscription-id" => 42, "cancel-renewal" => "");
$http_query = http_build_query($query);

This will return ?subscription-id=42&cancel-renewal=. And works perfectly fine with isset()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.