PHP - 在list()参数中将字符串转换为int?

The*_*lob 2 php casting

我正在改进我的代码,我有几个地方需要将字符串转换为整数,但list()函数的限制正在阻止我使用list().具体例子:

$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];
Run Code Online (Sandbox Code Playgroud)

我想做什么(但得到一个致命的错误)让事情变得更加整洁:

list((int)$month, (int)$day, (int)$year) = explode("-", $x); // I want echo(gettype) ---> integer for each variable
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,或者我能做到以下几点是最好的?

list($month, $day, $year) = explode("-", $x);

$month = (int)$month;
$day   = (int)$day;
$year  = (int)$year;
Run Code Online (Sandbox Code Playgroud)

Ana*_*Die 8

通过这个参考: -

如何将数组值从字符串转换为int?

你可以这样做: -

list($month, $day, $year) = array_map('intval', explode('-', $x));
Run Code Online (Sandbox Code Playgroud)