Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

5 Answers 5

up vote 4 down vote accepted

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);
share|improve this answer
    
Doh yes of course. Being an idiot...long day. Going to turn the computer off now. –  johnwards Jul 5 '10 at 20:02

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

share|improve this answer

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
share|improve this answer

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()

share|improve this answer

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);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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