0

How would you refactor something like this:

$start = $_GET['s'];
if (!is_int($start) || $start < 0)
{
    $start = 0;
}

Here I need start to equal 0 or greater, however later on I will need it to equal 1 or greater. How would this be made into a function?

2
  • Why would you want to make this into a function? I can't really see anything in dire need of refactoring here to be honest Commented Feb 6, 2011 at 14:05
  • Sorry I had two windows open so I mistyped the title. Commented Feb 6, 2011 at 15:25

5 Answers 5

3

There is a builtin for that:

print max($_GET["s"], 0);

It still requires the (int) typcast though, and I would apply it to the $_GET access directly.

Sign up to request clarification or add additional context in comments.

Comments

1

This code will not work. $_GET will return a string. is_int will always fail. You should use is_numeric or typecast to int.

function minimal($value, $min)
{
    $value = (int)$value;
    if ($value < $min)
    {
        return $min;
    }
    return $value;
}

Comments

0
function positiveInt($value, $maxValue = 0) {
    $value = (int) $value;
    return ( $value < $maxValue ) ? $maxValue : $value;
}

$start = positiveInt($_GET['s']);

$start = positiveInt($_GET['s'], 5);

Comments

0
function myFunction($getparam, $equals){
  if(!is_int($getparam) || $getparam < $equals)
    return $equals
  return 'your actual return value';     
}

Is that what you intend to do :)?

Comments

0

Using the ternary operator can be helpful. Not everyone finds ternary operations to be easily readable. A matter of preference, I suppose.

function unsignedInt($int) {
    return (int) $int >= 0 ? (int) $int : 0;
}

$start = unsignedInt($_GET['s']);

Although this could still potentially show warnings (the function doesn't ensure $_GET['s'] exists), so I would personally probably declare my expected get vars at the top of the script:

$_GET['s'] = isset($_GET['s']) ? $_GET['s'] : '';

And since the function is incredibly similar, I might do it all in that variable declaration instead of going with the function:

$start = isset($_GET['s']) && (int) $_GET['s'] >= 0 ? (int) $_GET['s'] : 0;

So I suppose it depends on how you plan to use this method in your code.

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.