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();
Tunaki
  • 132,869
  • 46
  • 340
  • 423

2 Answers2

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.

Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51
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();
Pooya
  • 6,083
  • 3
  • 23
  • 43
  • @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 – Pooya Mar 31 '16 at 21:35