开发者

unset() from array versus if inside loop?

开发者 https://www.devze.com 2023-01-14 04:25 出处:网络
I\'m making a pagination script. As part of it, it will need to reconstruct the query string, minus $_GET[\'page\'].

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

Generates a URL-encoded query string from the associative (or indexed) array provided.

When working with such small loops, speed considerations are absolutely meaningless. Code readability comes above everything!

NULL is identical to an empty string, so it's down to taste which one you want to use.


You might also use the http_build_query() function for that. Try something like this:

$vars = $_GET;
unset($vars ['page']);
$queryString = http_build_query($vars , '', '&');
0

精彩评论

暂无评论...
验证码 换一张
取 消