0

I have the below function which checks if there are any values in two variables and then adds them up, or tells you if there aren't any. It actually works totally fine, BUT it also returns warnings for undefined variables when I leave them empty. Can anyone explain why this is? and how I can correct it?

I have searched but perhaps because of my lack of general knowledge on the subject I couldn't search efficiently.

function add_up($first, $second){
  if($first == "" and $second == ""){
    return 'No numbers';}
  else {
    return $first + $second;
  }
}
echo add_up();
6
  • 1
    Possible duplicate of Correct PHP code to check if a variable exists Commented Mar 31, 2016 at 21:15
  • If you mean that if just leave it empty and call the function without any arguments, then it is simply because you are doing it wrong. Commented Mar 31, 2016 at 21:16
  • @Rizier123 It may just be for the sake of an example. As doing this is useful when you are checking for POST data. Commented Mar 31, 2016 at 21:18
  • How you calling the function when you getting error? Commented Mar 31, 2016 at 21:18
  • @ShaifulIslam They are just getting warning messages, the call is at the end of the code block: add_up(). Commented Mar 31, 2016 at 21:24

2 Answers 2

1

In order to specify a function argument as optional you must define a default value for it:

function add_up($first = '', $second = ''){
  if($first == "" and $second == ""){
    return 'No numbers';}
  else {
    return $first + $second;
  }
}
echo add_up();

The warning represents the fact that both arguments are required (since they have no default values defined) meaning the function must be called with both arguments.

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

Comments

0

You may looking for something like this:

function add_up($first, $second){
  if(!isset($first, $second)){
    return 'No numbers bitch';}
  else {
    return $first + $second;
  }
}
echo add_up();

1 Comment

@RyanVincent you are correct but what I measured here was that the user may send some unset values or calling add_up(null, null) still it will give error. with my solution you can skip that at least. but you are right about the default values too

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.