PHP is a widely used programming language that supports a variety of data types, including numbers, strings, Boolean values, objects, arrays, etc. Sometimes in the process of writing code, you need to determine whether a variable is an array or a time. In this article, we will introduce how to use PHP to determine whether the data is an array or a time.
Judge whether a variable is an array
To determine whether a variable is an array, PHP provides two methods: is_array() function and gettype() function.
The is_array() function is a PHP built-in function used to check whether a variable is an array. Returns true if the given variable is an array, false otherwise. Usage examples are as follows:
$arr = array(1, 2, 3); if (is_array($arr)) { echo '$arr 是数组'; } else { echo '$arr 不是数组'; }
The output result is: $arr is an array
gettype() function is a PHP built-in function that returns variable type, the return value is a string. For array variables, the return value of the gettype() function is "array". The following is an example of using the gettype() function:
$arr = array(1, 2, 3); if (gettype($arr) === "array") { echo '$arr 是数组'; } else { echo '$arr 不是数组'; }
The output result is: $arr is an array
You can easily determine whether a variable is an array through the above two methods.
Judge whether a variable is time
PHP provides a variety of ways to determine whether a variable is time. The most common way is to use the strtotime() function and the DateTime object.
The strtotime() function is a function that can parse human-readable dates and times into UNIX timestamps, or integers. Convert timestamp to human-readable date and time format. Use the strtotime() function to convert a variable into a timestamp. If the return value is 0, it means that the variable is not of time type, otherwise it means that the variable is of time type. The following is an example of using the strtotime() function:
$date = '2021-08-05 14:30:00'; if (strtotime($date) === 0) { echo '$date 不是时间'; } else { echo '$date 是时间'; }
The output result is: $date is the time
DateTime is PHP A very useful time processing class, which provides many methods to handle dates and times. When using a DateTime object, you can use the catch statement to catch exceptions to determine whether the variable is of time type. The following is an example of using a DateTime object:
$date = '2021-08-05 14:30:00'; try { $datetime = new DateTime($date); echo '$date 是时间'; } catch (Exception $e) { echo '$date 不是时间'; }
The output result is: $date is time
The above is how to use PHP to determine whether a variable is an array or a time. I hope this article can help you with programming. Work helps.
The above is the detailed content of How to check whether the data is an array or time in php. For more information, please follow other related articles on the PHP Chinese website!