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..

my api {url}/details?limit=25&amount=99.9 sometimes amount is 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..

>Solution :

I think $request->amount will always return a string since the URL query parameters are also strings.

is_numeric() finds whether a variable is a number or a numeric string. In your case, it is returning true because it is a numeric string.

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

Alternatively, if the behaviour of float and int inputs are the same, you could also do:

$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;

Leave a Reply