0

I'm getting true or false from query string i don't have access to change this www.example.com?is_test=true

But in backend for database i'm excepting integer like 0,1

To achieve this i'm trying like this

(int) (boolean) 'true' //gives 1
(int) (boolean) 'false' //gives 1 but i need 0 here

Event i tried

$test = "false";
$bool = settype($test, 'boolean'); //it was giving true

(int) $bool also gives 1

i'm not sure there might be some other better php function to achieve this? Or any better way to this please suggest

Yah ternary operator is one best option But is there any other options for conversion

vijaykumar
  • 4,658
  • 6
  • 37
  • 54

5 Answers5

2

PHP can't read your strings. You'll have to use some kind of if-else construction:

if ($GET['is_test'] === 'false') {
    return 0;
} else {
    return 1;
}
KWeiss
  • 2,954
  • 3
  • 21
  • 37
1

what about simply:

(!empty($_GET['is_test']) && $_GET['is_test'] === 'true' ? 1 : 0)

Edit: Here you are checking the existence of the variable so you don't get a notice error.

CUGreen
  • 3,066
  • 2
  • 13
  • 22
  • @PathikVejani A code-only answer might not be a good one, but it's still an answer. I would recommend you this post about the LQPRQ: [You're doing it wrong: A plea for sanity in the Low Quality Posts queue](http://meta.stackoverflow.com/questions/287563/youre-doing-it-wrong-a-plea-for-sanity-in-the-low-quality-posts-queue) – FelixSFD Jan 18 '17 at 09:03
1

The current answers are perfect. However, for maintenance and readability, you could easily make a parser class to complete these actions. Like this for example:

namespace Parser;

class Convert
{
    public static function StringToBoolean(
        $string
    ) {
        if(strpos('true', $string) || strpos('false', $string)) {
            return strpos('true', $string) ? true : false;
        }
        throw new Exception("$string is not true or false.");
    }
}

Then any time you want to use it, you can manually type the string or use a variable to convert.

echo (int) $example = Parser\Convert::StringToBoolean('true');   // 1
$stringBool = 'false';
echo (int) $example = Parser\Convert::StringToBoolean($stringBool);  // 0
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
0

As mentioned by @vp_arth this was best option

echo intval($_GET['is_test'] === 'true') //gives 0,1 for false,true
vijaykumar
  • 4,658
  • 6
  • 37
  • 54
-1
if(isset($_GET['is_test']))
{
    return ($_GET['is_test']=="true") ? 1 : 0;
}

You can just use ternary option

M A SIDDIQUI
  • 2,028
  • 1
  • 19
  • 24