[英]why my value is always taking as string in laravel?
我正在接受用戶的請求並將其存儲在$request
變量中,基於此我正在獲取一些關鍵值,直到它工作正常,之后我將此值傳遞給 switch case 語句如果該值意味着什么是double/float
類型,它會在這種情況下執行一些操作,對於string and integer
也類似。但即使我通過integer or double/float
類型,它也會string
幫助我解決這個問題。 .
我的 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
}
}
無論傳遞的值是什么,它都被視為字符串類型,只有我需要解決這個問題,請幫助我..
我認為$request->amount
將始終返回一個字符串,因為 URL 查詢參數也是字符串。
is_numeric()
確定變量是數字還是數字字符串。 在您的情況下,它返回 true 因為它是一個數字字符串。
你可以這樣做:
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
}
或者,如果float
和int
輸入的行為相同,您也可以這樣做:
$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.