Type casting while array destructuring
| From: | Enno Woortmann | Date: | Tue, 24 Mar 2020 13:32:35 +0000 |
| Subject: | Type casting while array destructuring | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-109270@lists.php.net to get a copy of this message | ||
Hi,
currently when using array destructuring the variables are assigned as
they are. For example we split a string with explode all variables will
contain strings:
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
[$user, $pass, $uid, $gid, $gecos, $home, $shell] = explode(":", $data);
If we want to write functions consuming $uid and $gid as integer values
with strict types enabled we need to cast the values afterwards:
$uid = (int) $uid;
$gid = (int) $gid;
// or during the function call
$myConsumingObject->myConsumingFunction((int) $uid, (int) $gid);
I think you get my point. How about adding some syntactic sugar and
allow type casting inside the detructuring expression?
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
[$user, $pass, (int) $uid, (int) $gid, $gecos, $home, $shell] =
explode(":", $data);
// $uid and $gid are integer values now. All other variables remain as
they are and contain strings
An example with associative arrays in loops:
$array = [
[ 'name' => 'a', 'id' => '1' ], [ 'name' => 'b', 'id' => '2' ],]; foreach ($array as ['id' => (int) $id, 'name' => $name]) {
// $id contains integer values} Further thoughts: when using the list() reference assignment implemented in PHP7.3 the referenced value could be casted (something to discuss about, maybe as future scope as casting a reference assignment currently isn't supported): $array = [1, 2]; [(string) $a, (string) &$b] = $array; // $a would be a string: '1' // $b would be a string: '2' // $array would contain one integer and one string element: [1, '2'] Thoughts?