I am refining my code and I have a couple of spots where I need to cast strings as integer but the limitations of the list() function are dissuading me from using list()
. Specific example:
$x = '12-31-2010';
$explode = explode("-", $x);
// Need to do the following because e.g. echo gettype($explode[0]) ---> string
$month = (int)$explode[0];
$day = (int)$explode[1];
$year = (int)$explode[2];
What I would like to do (but get a fatal error) to make things a little more tidy:
list((int)$month, (int)$day, (int)$year) = explode("-", $x); // I want echo(gettype) ---> integer for each variable
Is there any way to do this or is the best I can do the following?
list($month, $day, $year) = explode("-", $x);
$month = (int)$month;
$day = (int)$day;
$year = (int)$year;
By this reference:-
how to convert array values from string to int?
you can do it like below:-
list($month, $day, $year) = array_map('intval', explode('-', $x));
If you need the same type for each element in the array, you can pass the array through array_map
before you assign it to the list(...)
:
$x = '12-31-2010';
list($month, $day, $year) = array_map('intval', explode("-", $x));