Home > front end >  if statement in php not respecting false case
if statement in php not respecting false case

Time:01-28

PHP is still new to me so excuse me if I am missing something basic here.

I have some very simple code:

echo $_GET['initState'];

            if ($_GET['initState']) {
                $num = 10;
            }
            else {
                $num = PHP_INT_MAX;
            }

            echo $num;

And when I check my logs, I see the following: false10

So initState is false, and yet num is assigned to 10

But when I change the code to the following:

echo $_GET['initState'];

            if ($_GET['initState'] == 1) {
                $num = 10;
            }
            else {
                $num = PHP_INT_MAX;
            }

            echo $num;

My output is now working correctly: false9223372036854775807

What am I missing here?

Here is the @GET code:

@GET("getreleases.php")
    Call<ReleaseModelResponse> getReleases(@Query("initState") boolean initState);

Appreciate any insight that can be provided here.

EDIT Actually, maybe my code is not working correctly in either case, which is why I have been looking closely at this problem for a while now. I noticed my activity was always loading more than 10 items so this must mean neither versions of the code work correctly for me.

Just to be sure, I checked my logs again when performing an action that results in initState being true, and this is what I see: true9223372036854775807

CodePudding user response:

In the first version of your code, the if statement is checking if the value of $_GET['initState'] is "truthy". In PHP, any non-empty string, non-zero number, or non-null value is considered "truthy". So even though the value of $_GET['initState'] is "false", it is still considered "truthy" in the if statement; therefore $num is assigned the value of 10.

In the second version of your code, you are explicitly checking if the value of $_GET['initState'] is equal to 1. Since it is not equal to 1, the else block is executed and $num is assigned the value of PHP_INT_MAX.

It seems that you are using this code in a REST API and sending a boolean value in the query parameter, but in PHP, booleans are not directly passed in query parameters, instead they are passed as strings "true" or "false", so in the first version of your code, the value of $_GET['initState'] is "false" string and its considered truthy, but in the second version, the value of $_GET['initState'] is "false" string and you are comparing it with 1, which is not equal and it's not truthy.

You could try to change the if($_GET['initState'] == 1) to if($_GET['initState'] === "true") or if($_GET['initState'] == true), this will check for the boolean value and not the string.

  •  Tags:  
  • php
  • Related