note 33366 deleted from function.explode by bjori
| From: | bjori@php.net | Date: | Mon, 25 Sep 2006 08:13:42 +0000 |
| Subject: | note 33366 deleted from function.explode by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117608@lists.php.net to get a copy of this message | ||
Note Submitter: gnif at never_mind dot com
----
This alters a parameter in a query string, if it doesn't exist adds it. May be useful to
someone out there, it is a good example of the explode and implode functions. This code has been
tested and proven working, there may allready be a function here that does this, I didn't have
time to check all the posts.
<?php
function AlterQueryStr($querystr, $param, $value) {
$vars = explode("&", $querystr);
$set = false;
for ($i=0;$i<count($vars);$i++) {
$v = explode('=',$vars[$i]);
if ($v[0] == $param) {
$v[1] = $value;
$vars[$i] = implode('=', $v);
$set = true;
break;
}
}
if (!$set) {$vars[] = $param . '=' . $value;}
return ltrim(implode('&', $vars), '&');
}
?>
Examples and Results:
AlterQueryStr('page=index&print=1&color=red', 'print', '0');
'page=index&print=0&color=red'
AlterQueryStr('page=index&print=1', 'color', 'red');
'page=index&print=1&color=red'
AlterQueryStr('', 'foo', 'bar');
'foo=bar'
--
http://spacevs.com