Hy guys, i have a problem.
My variable can have different values in my cycle:
- values="10"
- values="Hello"
- values="2015-02-17"
How do I check the type of variable with a condition? I have tried but string type is "equal" to date type.
You can try the php gettype() function to find the type
strtotime() function which will convert to a time stamp so that you can distinguish date and stringThere are a variety of built-in functions in PHP, mainly beginning with is_
is_a is_a — Checks if the object is of this class or has this class as one of its parentsis_array — Finds whether a variable is an arrayis_binary — Finds whether a variable is a native binary stringis_bool — Finds out whether a variable is a booleanis_buffer — Finds whether a variable is a native unicode or binary stringis_callable — Verify that the contents of a variable can be called as a functionis_dir — Tells whether the filename is a directoryis_double — Alias of is_float()is_executable — Tells whether the filename is executableis_file — Tells whether the filename is a regular fileis_finite — Finds whether a value is a legal finite numberis_infinite — Finds whether a value is infiniteis_int — Find whether the type of a variable is integeris_link — Tells whether the filename is a symbolic linkis_nan — Finds whether a value is not a numberis_null — Finds whether a variable is NULLis_numeric — Finds whether a variable is a number or a numeric stringis_object — Finds whether a variable is an objectis_readable — Tells whether a file exists and is readableis_resource — Finds whether a variable is a resource is_scalar — Finds whether a variable is a scalarThere are a few others - some are aliases of some mentioned here - others not. The PHP manual will offer far more information on each but they can be used to form the backbone of a logical test for your variables.
It's a bit hacky but you could so something like:
function dataType($data) {
// is_numeric() will validate ints and floats
if(is_numeric($data)) return "number";
// if $data is not a valid date format strtotime() will return false
// so we're just using it as a validator basically
elseif(strtotime($data)) return "date";
// is_string() does what you'd expect
elseif(is_string($data)) return "string";
// anything else that you're not looking for
else return "other";
}
echo dataType("Hello"); // outputs "string"
There would be issues with is_numeric() however if your numbers use , separators in any way, for instance NL number formating 1,5 or UK formatting with thousand separators 1,000,000.
You could get around this with the number_format() function if that's the case: http://php.net/manual/en/function.number-format.php
"2015-02-17"and"Hello"are strings ... are you expecting something different? Technically even"10"would be a string as it's in"marks."2015-02-17"would be a date is if you made it one in the first place with something likenew DateTime('2015-02-17')(which would be aDateTimeobject) ... otherwise it is just a string.