Skip to content
PHP Logo

How can a PHP function differentiate between a numeric value and a string input when converting to a timestamp?

When converting a value to a timestamp in PHP, the function can differentiate between a numeric value and a string input by using the `is_numeric()` function to check if the input is numeric. If the input is numeric, it can be directly converted to a timestamp using the `strtotime()` function. If the input is a string, additional checks can be performed to handle different date formats before converting it to a timestamp.

php
function convertToTimestamp($input) {
    if (is_numeric($input)) {
        return $input; // Assuming numeric input is already a timestamp
    } else {
        $timestamp = strtotime($input);
        if ($timestamp === false) {
            // Handle different date formats or invalid input
            return false;
        } else {
            return $timestamp;
        }
    }
}

// Example usage
$numericInput = 1609459200; // Numeric timestamp value
$stringInput = "2021-01-01"; // Date string
echo convertToTimestamp($numericInput) . "\n";
echo convertToTimestamp($stringInput) . "\n";