Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
array key casting
<?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;
}
}
<?php
function array_change_key_type_string(array $array)
{
$obj = new stdClass();
foreach($array as $key => $value){
$obj->{$key} = $value;
}
return (array) $obj;
}
<?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