简体   繁体   English

为什么我的值总是在 laravel 中作为字符串?

[英]why my value is always taking as string in laravel?

I am taking the request from the user and store it in $request variable based on this i am fetching some key value up to this it's working fine,after this i am passing this value to the switch case statement what it does means if the value is double/float type it will do some operations inside that case, similarly for string and integer also.but even if i pass integer or double/float type it will go the string case only.can you please help me where did i mistake..我正在接受用户的请求并将其存储在$request变量中,基于此我正在获取一些关键值,直到它工作正常,之后我将此值传递给 switch case 语句如果该值意味着什么是double/float类型,它会在这种情况下执行一些操作,对于string and integer也类似。但即使我通过integer or double/float类型,它也会string帮助我解决这个问题。 .

my api {url}/details?limit=25&amount=99.9 sometimes amount is 99 or NinteyNine我的 api {url}/details?limit=25&amount=99.9有时金额是99 or NinteyNine

Public function run(){
$request=new Request();
$value=$request->amount;
switch(gettype($value)){
 case 'double':
    //perform some logic if type is double
   break;
 case 'string':
   //perform some logic if type is string
    break;
 default:
   //perform some logic if type is Integer 
}
}

what ever the value is passed it's considered as a string type only i need to fix this issue please help me..无论传递的值是什么,它都被视为字符串类型,只有我需要解决这个问题,请帮助我..

I think $request->amount will always return a string since the URL query parameters are also strings.我认为$request->amount将始终返回一个字符串,因为 URL 查询参数也是字符串。

is_numeric() finds whether a variable is a number or a numeric string . is_numeric()确定变量是数字还是数字字符串 In your case, it is returning true because it is a numeric string.在您的情况下,它返回 true 因为它是一个数字字符串。

You could do:你可以这样做:

function amountType(string $amount): string {
    if (is_numeric($amount)) {
        if ((int) $amount == (float) $amount) {
            return "int";
        }

        return "float";
    }
    
    return "string";
}

$type = amountType($request->amount);

switch($type) {
    case 'float':
        //perform some logic if type is double
        break;
    case 'string':
        //perform some logic if type is string
        break;
    case 'int':
        //perform some logic if type is Integer
        break;
    default:
        // Invalid type
}

Snippet: https://3v4l.org/K9XVB代码段: https://3v4l.org/K9XVB

Alternatively, if the behaviour of float and int inputs are the same, you could also do:或者,如果floatint输入的行为相同,您也可以这样做:

$amount = $request->amount;

if (is_numeric($amount)) {
    $numericAmount = (float) $amount;
    // Perform some logic if input is numeric
    return;
}

// Perform some logic if input is string
return;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM