If I had a simple array where every value is a string, how would I be able to convert every value to the correct data-type? Example:
$array = array(
"stringExample" => "string",
"floatExample" => "1.24",
"intExample" => "1",
"boolExample" => "TRUE"
);
Obviously, the float, integer and boolean are all strings since that's how they are put in the array. But I want the float to be an actual float, the integer to be an actual integer and so on. For small or fixed datasets, I could simply convert them one by one, but when dealing with large amounts of data and/or dynamic data, that would be impracticable. What is should have to be is:
$array = array(
"stringExample" => "string",
"floatExample" => 1.24,
"intExample" => 1,
"boolExample" => true
);
The only other method I could think of is to make a loop that checks every value to see if it's a float, bool or else, but I feel like that's quite inefficient. Also because of the fact that it should only be converted if the value is ONLY a certain data-type. If the string was: "That's true", it should be a string, but if it's just "true", it should be a boolean. It also gets complicated with the 1 for example, since this can both be interpreted as a boolean and integer. But in my case, that should just be an integer and not a boolean.
Does someone have an efficient way to achieve this? Is it smart to do in the first place? Maybe some kind of array filter? Any help is appreciated!
forloop and convert them one by one. I wouldn't worry about it being inefficient until you really start to notice performance problems. This is especially true if you know what type each key is supposed to be. Like, wouldfloatExamplebe known ahead of time to be a float, or would you need to test every value to guess what type it should be? If it's the former, and you know the type corresponding to each key, I'd just loop through it and not worry.filter_varor combinations ofctype_digitoris_int/is_numeric/is_string/etc and just loop over values. I would probably go from simpler types to complex, checking for bool, then int, then float, then string, etc, to hopefully reduce the chance you don't cast to the most appropriate type.(int) $array['intExample']FILTER_VALIDATE_INT,FILTER_VALIDATE_FLOATandFILTER_VALIDATE_BOOLand it works like a charm. I didn't really realize that it's essentially just those 3 data-types that I needed.