Here isare some tips:
- NameThe name of the function should be clearer.
- Try to avoid ctype_digit
ctype_digit
usage, because it may produce unexpected results - ctype_digit(42)ctype_digit(42)
returns FALSEFALSE
. - Because you are working with integers, you should cast values to integers, note. Note that inputs are always strings.
- You must check for negative values, also as well.
- Second can be 0 for. For example: 2 min and 0 sec. Also, some songs can lasts lower thenlast less than a minute (Classicclassic songs)
- Consider that some CD songsongs may have a duration of more thenthan 60 minmins, CD medium can store 80min and80 mins (and it can be one song), and some mix or classic songs. So, maybe you should avoid a minute check.
59) {
$warning['sec'] = 'The seconds must be between 0 and 59';
}
if($min 60) {
$warning['min'] = 'The minutes must be between 0 and 60';
}
// for songs bigger then 60 minutes
if($min == 60 && $sec > 0) {
$warning['duration'] = "Song must last more then one second and maximum 60 minutes.";
}
return !empty($warning) ? $min * 60 + $sec : NULL;
}
<?php
$warning = array();
/**
* Validate song duration
* @param $min
* @param $sec
* @param $required
* @return int|NULL
*/
function validate_duration($min, $sec, $required = false) {
global $warning;
$min = (int) $min;
$sec = (int) $sec;
if($required && $min == 0 && $sec == 0) {
$warning['duration'] = "The duration is a required field.";
return NULL;
}
if($sec < 0 OR $sec > 59) {
$warning['sec'] = 'The seconds must be between 0 and 59';
}
if($min < 0 OR $min > 60) {
$warning['min'] = 'The minutes must be between 0 and 60';
}
// for songs bigger then 60 minutes
if($min == 60 && $sec > 0) {
$warning['duration'] = "Song must last more then one second and maximum 60 minutes.";
}
return !empty($warning) ? $min * 60 + $sec : NULL;
}