Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading