0

I was wondering how can I convert the code below into a PHP function that works.

Here is my original code.

if(isset($_GET['cat'])) {
    $cat_name = strip_tags(filter_var($_GET['cat'], FILTER_SANITIZE_URL));
}

So far I got this for the function.

function cat(){
    if(isset($_GET['cat'])) {
        $cat_name = strip_tags(filter_var($_GET['cat'], FILTER_SANITIZE_URL));
    }
}
3
  • php.net/manual/en/functions.user-defined.php Commented Jul 7, 2011 at 4:49
  • and what is not ok with your function? Commented Jul 7, 2011 at 4:50
  • @Tudor Constantin its not working. Commented Jul 7, 2011 at 4:54

2 Answers 2

2

This will return the sanitized value or null if $_GET['cat'] is not set. When you call this function, you would need to check if the return value is null.

function get_cat() {
    $cat_name = null;
    if(isset($_GET['cat'])) {
        $cat_name = strip_tags(filter_var($_GET['cat'], FILTER_SANITIZE_URL));
    }
    return $cat_name;
}
Sign up to request clarification or add additional context in comments.

5 Comments

how would I call the function?
Just call it via get_cat(), or $cat = get_cat() to save the value.
this aint working I get the following error Undefined variable: cat_name
This works for me. (Note that I left out the opening brace on the first line. Fixed now.) How are you calling the function?
If one these answers works for you, please consider accepting.
0

I would do:

function get_cat($GET) 
    $cat_name = null;
    if(isset($GET['cat'])) {
        $cat_name = strip_tags(filter_var($GET['cat'], FILTER_SANITIZE_URL));
    }
    return $cat_name;
}

And to call it, just do:

$cat = get_cat($_GET);

With this, the get_cat function is encapsulated (doesn't depend on external vars).

Just my 2 cents. Hope this helps. Cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.