Jump to content

Functions - Multiples of same


zimmo

Recommended Posts

I have a function that just checks the field is numeric only. I need this function to do the same thing for each day of the week. Rather than duplicating the function and changing the values, I know there must be an easier way to loop through each one and have just one function call.

 

Here is the function:

 

function validNumber($monday) {

if(is_numeric($monday)) 
{
	$isValid = true;
}
else
{
	$isValid = false;
}
return $isValid;
}

 

So rather than duplicating the above function and calling it for example function validNumber2 etc.. and then changing the days in the function, is their a way to write this so it covers all days $monday, $tuesday etc..etc.

 

Link to comment
https://forums.phpfreaks.com/topic/199793-functions-multiples-of-same/
Share on other sites

That function is pretty unnecessary.

 

function validNumber($monday) {
   if(is_numeric($monday)) {
      $isValid = true;
   }
   else {
      $isValid = false;
   }
   return $isValid;
}

 

Is exactly the same as just using

is_numeric($monday)

You could extend your function like:

 

function validNumber($number) {
    $number = (array) $number;
    $isValid = true;
    foreach ($number as $num) {
        if (!is_numeric($num)) {
            $isValid = false;
            break;
        }
    }
    return $isValid;
}

Is exactly the same as just using

is_numeric($monday)

 

Thanks, did not know that one. I have just tried this then rather than calling a function, and this is not giving me the error, its treating it as if its numbers when I enter letters.

 

if ( empty($monday) ) {
  $error['monday_error'] = '<div class="formerror">Please enter your price. eg. 7.00</div>';
}
elseif (is_numeric($monday)) {
$error['monday_error'] = '<div class="formerror">Please enter numbers only.</div>';
}

Half asleep, I should go back to bed.

 

Fixed it:

if ( empty($monday) ) {
  $error['monday_error'] = '<div class="formerror">Please enter your price. eg. 7.00</div>';
}
elseif (!is_numeric($monday)) {
$error['monday_error'] = '<div class="formerror">Please enter numbers only.</div>';
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.