Skip to content

Instantly share code, notes, and snippets.

@codearachnid
Created September 2, 2024 00:44
Show Gist options
  • Save codearachnid/7b012c5f70c2bc8b507050d430d4fe88 to your computer and use it in GitHub Desktop.
Save codearachnid/7b012c5f70c2bc8b507050d430d4fe88 to your computer and use it in GitHub Desktop.
variety of values and convert to a boolean sql value
<?php
function toSqlBoolean($value) {
// Convert the value to a boolean first
$booleanValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// Return SQL boolean equivalent
return $booleanValue ? 1 : 0;
}
// Usage examples
echo toSqlBoolean(true); // Outputs: 1
echo toSqlBoolean(false); // Outputs: 0
echo toSqlBoolean("true"); // Outputs: 1
echo toSqlBoolean("false"); // Outputs: 0
echo toSqlBoolean("yes"); // Outputs: 1
echo toSqlBoolean("no"); // Outputs: 0
echo toSqlBoolean(1); // Outputs: 1
echo toSqlBoolean(0); // Outputs: 0
echo toSqlBoolean("1"); // Outputs: 1
echo toSqlBoolean("0"); // Outputs: 0
echo toSqlBoolean(null); // Outputs: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment