note 33366 modified in function.explode by irchtml
| From: | irchtml@php.net | Date: | Thu, 05 Feb 2004 06:49:54 +0000 |
| Subject: | note 33366 modified in function.explode by irchtml | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-64667@lists.php.net to get a copy of this message | ||
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.
//-------------------
//-------------------
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
--was--
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.
//-------------------
//-------------------
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&color=red'
AlterQueryStr('page=index&print=1', 'color', 'red');
'page=index&print=1&color=red'
AlterQueryStr('', 'foo', 'bar');
'foo=bar'
--
http://spacevs.com
http://www.php.net/manual/en/function.explode.php