I am getting Warning: array_push() expects parameter 1 to be array, string given in ...
for array_push()
on this piece of code. The warning occurs in the first push, how do I fix this?
$url = $_SERVER['QUERY_STRING'];
$chunk = explode("&",$url);
array_pop($chunk);
foreach($chunk as $key => $value)
{
$pieces = explode("=",$value);
if($pieces)
{
$val = $pieces[0];
if(isset($$val))
{
array_push($$val,$pieces[1]);
}else{
$$val = array();
array_push($$val,$pieces[1]);
}
}
}
Note: I am not using $_GET because my querystring can contain multiple parameters with the same name like this
?q=1&q=2&q=3&q=4
You don't need to explode and push/pop the query string. Just use the $_GET superglobal.
http://php.net/manual/en/reserved.variables.get.php
Edit: $_GET is an array, you can loop over it in the same way as any other array. If you need to get all of them separately then you can do this:
foreach ($_GET as $key => $value) {
// whatever
}
Edit2: OK, I still think that whatever you are doing with those params is the wrong way to do it but if you need a function then you can try something like this:
function extractVars($url)
{
$query = explode('?', $url);
$extract = array();
if (!isset($query[1])) {
return $extract;
}
$params = explode('&', $query[1]);
foreach($params as $param) {
if (strpos($param, '=') !== false) {
list($key, $value) = explode('=', $param);
$extract[$key][] = $value;
}
}
return $extract;
}
$string = 'url?a=1&a=2&a=3&b=1&b=2&b=3';
print_r(extractVars($string));
Which gives an output like this:
Array
(
[a] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[b] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)