array key casting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function array_change_key_type(array $array, $type = T_STRING_CAST ) | |
{ | |
if($token === T_STRING_CAST) { | |
$obj = new stdClass(); | |
foreach($array as $key => $value){ | |
$obj->{$key} = $value; | |
} | |
return (array) $obj; | |
} else { | |
$new_array = []; | |
foreach($array as $key => $value){ | |
$new_array[ cast_by_token($key, $type) ] = $value; | |
} | |
return $new_array; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function array_change_key_type_string(array $array) | |
{ | |
$obj = new stdClass(); | |
foreach($array as $key => $value){ | |
$obj->{$key} = $value; | |
} | |
return (array) $obj; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function cast_by_token($variable, $token){ | |
if($token === T_UNSET_CAST) { | |
return (unset) $variable; | |
} | |
if($token === T_BOOL_CAST) { | |
return (bool) $variable; | |
} | |
if($token === T_OBJECT_CAST) { | |
return (object) $variable; | |
} | |
if($token === T_ARRAY_CAST) { | |
return (array) $variable; | |
} | |
if($token === T_STRING_CAST) { | |
return (string) $variable; | |
} | |
if($token === T_DOUBLE_CAST) { | |
return (double) $variable; | |
} | |
if($token === T_INT_CAST) { | |
return (int) $variable; | |
} | |
return $variable; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment