2

I was searching here on StackOverflow about converting string to the real value and i didn't found. I need a function like "gettype" that does something like the result above, but i can't do it all :s

gettypefromstring("1.234"); //returns (doble)1,234;
gettypefromstring("1234"); //returns (int)1234;
gettypefromstring("a"); //returns (char)a;
gettypefromstring("true"); //returns (bool)true;
gettypefromstring("khtdf"); //returns (string)"khtdf";

Thanks to all :)

3 Answers 3

7

1+ for Svisstack! ;)

Here is the function if someone want it:

function gettype_fromstring($string){
    //  (c) José Moreira - Microdual (www.microdual.com)
    return gettype(getcorrectvariable($string));
}
function getcorrectvariable($string){
    //  (c) José Moreira - Microdual (www.microdual.com)
    //      With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack)

    /* FUNCTION FLOW */
    // *1. Remove unused spaces
    // *2. Check if it is empty, if yes, return blank string
    // *3. Check if it is numeric
    // *4. If numeric, this may be a integer or double, must compare this values.
    // *5. If string, try parse to bool.
    // *6. If not, this is string.

    $string=trim($string);
    if(empty($string)) return "";
    if(!preg_match("/[^0-9.]+/",$string)){
        if(preg_match("/[.]+/",$string)){
            return (double)$string;
        }else{
            return (int)$string;
        }
    }
    if($string=="true") return true;
    if($string=="false") return false;
    return (string)$string;
}

I used this function to know if the number X is multiple of Y.

Example:

$number=6;
$multipleof=2;
if(gettype($number/$multipleof)=="integer") echo "The number ".$number." is multiple of ".$multipleoff.".";

But the framework that i work returns always the input vars as strings.

1
  • 1
    You have some extra code. empty already tests for an empty string. Why are you using || $striing == ""? Also, you're casting a string to a string. PHP knows that "" is a string. That line could be rewritten as: if (empty($string)) return "". Also, it doesn't make sense to do return (bool)true/false. true and false are already booleans; they don't need to be casted.
    – ryeguy
    Commented Apr 22, 2010 at 15:24
5

You must try to convert it in specified order:

  1. Check is double
  2. If double, this may be a integer, you must convert and compare this values.
  3. If not, this is char if lenght is == 1.
  4. If not, this is string.
  5. If string, try parse to bool.

You can't use gettype because you may get string type of decimal writed in string.

4
  • Thanks, i will try that way. Yes, i know, thats why i want this function ;)
    – cusspvz
    Commented Apr 22, 2010 at 13:39
  • Problem, and if the string has "12ab3"? it is string right? how can i know if the string has alphanumeric chars?
    – cusspvz
    Commented Apr 22, 2010 at 13:46
  • "12ab3" is not int, because have a alphanumeric, then algorithm not check double from it, they lenght is bigger than 1, then this is string, and cant parse it to bool. Result is string, and real result is string because "12ab3" is not a valid number.
    – Svisstack
    Commented Apr 22, 2010 at 14:41
  • i have added the function here as answer and with credits to you, thanks ;)
    – cusspvz
    Commented Apr 22, 2010 at 15:24
1

Here is an updated version of this 9 year old function:

/**
 * Converts a form input request field's type to its proper type after values are received stringified.
 *
 * Function flow:
 *      1. Check if it is an array, if yes, return array
 *      2. Remove unused spaces
 *      3. Check if it is '0', if yes, return 0
 *      4. Check if it is empty, if yes, return blank string
 *      5. Check if it is 'null', if yes, return null
 *      6. Check if it is 'undefined', if yes, return null
 *      7. Check if it is '1', if yes, return 1
 *      8. Check if it is numeric
 *      9. If numeric, this may be a integer or double, must compare this values
 *      10. If string, try parse to bool
 *      11. If not, this is string
 *
 * (c) José Moreira - Microdual (www.microdual.com)
 * With the help of Svisstack (http://stackoverflow.com/users/283564/svisstack)
 *
 * Found at: https://stackoverflow.com/questions/2690654/how-to-get-the-real-type-of-a-value-inside-string
 *
 * @param  string $string
 * @return mixed
 */

function typeCorrected($string) {
    if (gettype($string) === 'array') {
        return (array)$string;
    }

    $string = trim($string);

    if ($string === '0') { // we must check this before empty because zero is empty
        return 0;
    }

    if (empty($string)) {
        return '';
    }

    if ($string === 'null') {
        return null;
    }

    if ($string === 'undefined') {
        return null;
    }

    if ($string === '1') {
        return 1;
    }

    if (!preg_match('/[^0-9.]+/', $string)) {
        if(preg_match('/[.]+/', $string)) {
            return (double)$string;
        }else{
            return (int)$string;
        }
    }

    if ($string == 'true') {
        return true;
    }

    if ($string == 'false') {
        return false;
    }

    return (string)$string;
}

I am using it in a Laravel middleware to transform form values that were stringified by browser JavaScript's FormData.append() back into their correct PHP types:

public function handle($request, Closure $next)
{
    $input = $request->all();

    foreach($input as $key => $value) {
        $input[$key] = $this->typeCorrected($value);
    }

    $request->replace($input);

    return $next($request);
}
  1. To create that, type in your CLI php artisan make:middleware TransformPayloadTypes.

  2. Then paste in the above handle function.

  3. Don't forget to paste in the typeCorrected function also. I currently recommend making it a private function in your middleware class, but I don't claim to be a super-expert.

You can imagine that $request->all() is an array of key/value pairs, and it comes in with all values stringified, so the goal is to convert them back to their true type. The typeCorrected function does this. I've been running it in an application for a few weeks now, so edge cases could remain, but in practice, it is working as intended.

If you get the above working, you should be able to do something like this in Axios:

// note: `route()` is from Tightenco Ziggy composer package
const post = await axios.post(route('admin.examples.create', {
    ...this.example,
    category: undefined,
    category_id: this.example.category.id,
}));

Then, in your Laravel controller, you can do \Log::debug($request->all()); and see something like this:

[2020-10-12 17:52:43] local.DEBUG: array (
  'status' => 1,
  'slug' => 'asdf',
  'name' => 'asdf',
  'category_id' => 2,
) 

With the key fact being that you see 'status' => 1, and not 'status' => '1',

All of this will allow you to submit JSON payloads via Axios and receive non-nested values in your FormRequest classes and controllers as the actual payload types are mutated. I found other solutions to be too complex. This above solution allows you to submit flat JSON payloads from pure JavaScript easily (so far, haha).

1
  • This is a very helpful answer. Commented Oct 22, 2020 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.