Matt Smeets
Matt Smeets

Reputation: 398

Boolean to integer in php

I am currently using checkboxes in a form and want to save the checkbox value into a database column of type int. What would be the most efficient way to achieve this. I have already tried casting the variable to a (int) but this has not done anything for me yet.

HTML: <input name='active' id='active' ng-model='formData.active' ng-init='formData.active=true' type="checkbox"> Active </br>


PHP:
$active = (int) $_POST['active'];
echo $active;
echo $_POST['active'];

Output:
0
true

Note: I am trying to implement this without an awful if statement or switch.

Upvotes: 0

Views: 1744

Answers (5)

Matt Smeets
Matt Smeets

Reputation: 398

Looking around in the PHP manual the following code can be found:

filter_var('FALSE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)

Reference: http://php.net/manual/en/function.filter-var.php#118356

Upvotes: 0

swisst
swisst

Reputation: 112

Fist of all, your input in HTML is "sticky" and in PHP you test "active". But anyway, try in PHP following test:

if (isset($_POST['sticky']) and ($_POST['sticky']=='on')) $active=1;
else $active=0;

Upvotes: 0

Shub
Shub

Reputation: 2704

add an value attribute in input tag

<input name='active' value='1' ...>

Now it should work the way you need.

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74615

The $_POST variable for the checkbox will only be set if the checkbox is checked, so you can use something like this:

$active = isset($_POST['active']) ? 1 : 0;

I suspect that you're getting the string "true" rather than a boolean "true", in which case you can use a similar construct:

$active = $_POST['active'] === "true" ? 1 : 0;

Upvotes: 1

Jacob Benny John
Jacob Benny John

Reputation: 71

solution in https://stackoverflow.com/a/29288171/3923450 should work,

but if you are looking for an inbuilt function, try

intval

Upvotes: 0

Related Questions