4

Hello I know all about http://www.php.net/manual/en/function.http-build-query.php to do this however I have a little problem.

It "handly" turns boolean values into ones and zeros for me. I am building a little PHP wrapper for the Stack Overflow api and parsing an option array and then sending this onto the api breaks things..(doesn't like 1 for true).

What I would like is a simple function to turn a single dimensional array into a query string but turning true/false into string values of true/false.

Anyone know of anything that can do this before I start re-inventing the wheel

4

I don't know of anything offhand. What I'd recommend is first iterating through the array and covert booleans to strings, then call http_build_query

E.g.

foreach($options_array as $key=>$value) :
    if(is_bool($value) ){
        $options_array[$key] = ($value) ? 'true' : 'false';
    }
endforeach;
$options_string=http_build_query($options_array);
Is this answer outdated?
|
1
  • Doh yes of course. Being an idiot...long day. Going to turn the computer off now. – johnwards Jul 5 '10 at 20:02
1

Try passing http_build_query true and false as strings instead of booleans. You may get different results.

Is this answer outdated?
|
1

If you just need to convert your true/false to "true"/"false":

function aw_tostring (&$value,&$key) {
  if ($value === true) {
    $value = 'true';
  }
  else if ($value === false) {
    $value = 'false';
  }
}

array_walk($http_query,'aw_tostring');

// ... follow with your http_build_query() call
Is this answer outdated?
|
0

Loop through each variable of the query string ($qs) and if bool true or false, then change value to string.

foreach($qs as $key=>$q) {
    if($q === true) $qs[$key] = 'true';
    elseif($q === false) $qs[$key] = 'false';
}

Then you can use the http_build_query()

Is this answer outdated?
|
0

have a look at my wheel:

function buildSoQuery(array $array) {
    $parts = array();
    foreach ($array as $key => $value) {
        $parts[] = urlencode($key).'='.(is_bool($value)?($value?'true':'false'):urlencode($value));
    }
    return implode('&', $parts);
}
Is this answer outdated?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.