I’m making a pagination script. As part of it, it will need to reconstruct the query string, minus $_GET['page'].
This is option 1:
#reconstruct the GETs minus $_GET['page']
$vars = $_GET;
unset($vars['page']);
$queryString = '';
foreach ($vars as $k=>$v){
$queryString .= '&'.$k.'='.$v;
}
This is option 2:
$vars = $_GET;
$queryString = '';
foreach ($vars as $k=>$v){
if ($k !== 'page'){
$queryString .= '&'.$k.'='.$v;
}
}
Is one better than the other in terms of either speed or good practice? Presumably unset would be marginally quicker, as it would stop as soon as it found what it was looking for whereas the other would perform the if for every loop?
Additionally, when initializing the $queryString is there a reason to choose NULL over empty string or does it make no difference to anything?
Do neither. Use
http_build_query().When working with such small loops, speed considerations are absolutely meaningless. Code readability comes above everything!
NULLis identical to an empty string, so it’s down to taste which one you want to use.