0

I want to use a function that adds a get-parameter depending on whether they are already available.

Not works:

$url1 = "index2.php";
function addget($url){
                if (strpos($url, '?')) {
                $url = $url . '&animal='.$param;
            }
            else {
                $url = $url . '?animal='.$param;
            }           
            return ($url);
        }

addget($url1);

Works, but I need a function:

    $url1 = "index2.php";
    if (strpos($url1, '?')) {
                    $url1 = $url1 . '&animal='.$param;
                }
                else {
                    $url1 = $url1 . '?animal='.$param;
                }
  • 2
    If you [turn on error displaying](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display), you should be seeing an "Undefined variable" notice, because you try to use `$param` in the function, which isn't passed in as a parameter. – El_Vanja Apr 27 '21 at 15:07
  • Does this answer your question? [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – El_Vanja Apr 27 '21 at 15:07
  • 1
    Aside from that, since you're returning the result from your function, you need to reassign the variable, e.g. `$modifiedUrl = addget($url1);` – El_Vanja Apr 27 '21 at 15:12
  • @El_Vanja thank you very much for both recommenation. Now it works. –  Apr 27 '21 at 15:27

1 Answers1

0

For building your query string, you might want to have a look at http_build_query as well:

$params = ['animal' => 'bird'];
$url    = 'https://www.example.com';

function expandQueryString($url, $params) {

    $params = http_build_query($params);
    return strpos($url, '?') ? $url.'&'.$params : $url.'?'.$params;
}

var_dump(expandQueryString($url, $params)); // https://www.example.com?animal=bird
nosurs
  • 680
  • 6
  • 13