When you have optional arguments that can have different types, which value is most suited to point out that the argument should not be taken into consideration? False or Null?
null is the value used to represent "no value", whereas false means "no", "bad", "unsuccessful", "don't" etc.
Therefore: null.
For me this depends on what I'm going to do with the value of said argument...
I am writing a database function where I can have default values as NULL
function somedbfunc($id = NULL, $column1 = NULL)
If these values are null my function may insert a blank record..
If I need to stop my function because of a non argument I may use FALSE
function blah($this = FALSE, $that = FALSE)
{
if ( ! $this || ! $that)
{
return FALSE;
....
So I am saying that both are totally valid, but it depends on the situation you find yourself in.
For optional arguments use null (generally).
Use null, if you need to differentiate between boolean values (true/false) and nothing (null). On the other hand if you don't need to check for not-set argument and you are using boolean variable then I'd go for false.
As you are saying that you want to tell the "optional arguments" "not be taken into consideration", I will go for null. False is explicitly saying "no" to the recipient. which is a valid input.
Related
I have a boolean field that is represented by 0 and 1 in my database.
if ($request->input('submitted')) {
// do code
}
This has been working because it's only been setting the field to 1 (true) but now there's a new flow that can revert the submission.
It has not been setting it back to 0 when I pass the value 0 in from the frontend and I assume it's because that condition is getting skipped since 0 would eval to null.
Is the best way to handle it:
if (isset($request->input('submitted'))) {
// do code
}
or would strictly checking against null work better:
if ($request->input('submitted') !== null) {
// do code
}
The simply approach parse your input to a boolean.
if ((bool) $request->input('submitted')) {
This will create the following results. Therefor removing your edge case.
(bool) "1" // true
(bool) "1" // false
An alternative approach is to use inbuilt PHP filter, it will parse a lot of cases more notably "true" and "false" to true and false.
if (filter_var($request->input('submitted'), FILTER_VALIDATE_BOOLEAN)) {
Codeigniter has a syntax for url parameter passing for functions inside the controller.
If a function for example:
function index($id){
$this->model->get_user($id);
}
Assuming that this function is called without supplying the ID namely called as
ProjectName/Controller/index
it will return an error as it expects a parameter.
Is there a way to check if a parameter exists.
No there is not a way to check if one exists per-say as that error happens before the controller has a chance to run code. ie. before the class method executes.
That said there is a simple workaround for this: You can supply a default value and check for that for example
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user($id);
}
}
This way when no parameter is supplied the ID will be null, this is fairly safe ( when using null ) because you can never supply null as part of the url path even doing this
www.mysite.com/index/null //or however the url works out in your case
Will supply null as a string, because everything in the url comes through as a string. So 'null' as a string is not in fact null it's just the word null. If that makes sense. So given that null could never be supplied and only happens if no other value is supplied.
In this case it may be worth casting the input to a int or further checking if it's an improper value.
This could be done several ways:
Casting:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user((int)$id);
//cast to int, things that are not INT or string equivalents become 0, which should not find a user as it would look for ID = 0
}
}
By Regx check:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else if( preg_match('/^[^\d]+$/', $id )){
// not an int ( contains anything other than a digit )
}else{
$this->model->get_user($id);
}
}
Cheers.
The documentation for filter_input() mentions :
Value of the requested variable on success, FALSE if the filter fails,
or NULL if the variable_name variable is not set.
After studying the various examples online, I was surprised to see that none of them (that I know of at least) checked for the value FALSE. Most of the examples only checked for the NULL value :
if ( is_null( filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING ) ) ) {
// display error
}
Is there a reason for this ? Or is there a real life example that does check for the FALSE value ? If so, would you kindly provide the example so that I may benefit from it.
Also, would you kindly provide the circumstances in which the filter_input could possibly fail. Much appreciated.
This is because !0 is true. Why? By adding the ! you are doing a boolean check, so your variable gets converted. And according to the manual:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
So the integer 0 gets converted to false while all other integers are converted to true.
This is why you need to do a type safe check for false or null as these are the values filter_input() returns if it fails for some reason
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
if ($name === false) {
//filter failed
}
if ($name === null) {
//variable was not set
}
In the PHP documentation for json_decode it says it can return TRUE,FALSE,NULL.
Could some help me understand when it would return FALSE? I understand invalid JSON will return NULL, but when would the other two be returned if not the actual JSON value?
Thanks
JSON format definition clearly shows all possible values and their representations:
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array.
Both objects and arrays have special syntax in JSON representation (wrapped in {} and [] respectively), so they can't be mixed up with false in any case. The same goes with string - it's wrapped in "" (double quotation marks). As for Numbers, they have to contain at least one digit - so cannot be confused with false (and true and null) too.
So that leaves us with the only case: when json_encode processes an object having redefined its JSON representation. For example (PHP 5.4+):
class FalsyFoo implements JsonSerializable {
public $foo;
public function __construct($f) {
$this->foo = $f;
}
public function jsonSerialize() {
return false;
}
}
$f = new FalsyFoo(true);
$fj = json_encode($f);
var_dump( $fj ); // string(5) 'false'
var_dump( json_decode($fj) ); // bool(false)
Technically, we still work with false value here, but the source is obviously different.
If you're still not convinced, check the source code of json_decode, which calls php_json_decode_ex after checking the arguments. This, in turn, calls parse_JSON_ex first, which operates over the predefined state transition table; the latter has only one set of states leading to false value as result. If this call fails somehow, value is checked directly:
if (str_len == 4) {
if (!strcasecmp(str, "null")) {
/* We need to explicitly clear the error
because its an actual NULL and not an error */
jp->error_code = PHP_JSON_ERROR_NONE;
RETVAL_NULL();
} else if (!strcasecmp(str, "true")) {
RETVAL_BOOL(1);
}
} else if (str_len == 5 && !strcasecmp(str, "false")) {
RETVAL_BOOL(0);
}
... and that's the only case when return_value is set to boolean.
The documentation says that values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. This means that if the booleans true orfalse are in the object to be encoded, they will be shows as TRUE or FALSE, and the same for null. For example:
json_decode('["hello",true]');
would return:
["hello",TRUE]
It doesn't mean that json_decode will return values of true, false, or null
For most of my models in CakePHP I often create a function that handles saving a record. The default behavior for a Model's save is to return the data array or false.
I prefer the function to return true/false only. So I cast the result to (bool). Is this a valid way to cast something to boolean?
It's never not worked, but I've often wondered if it was a poor practice.
public function queue($url,$order=0)
{
$result = $this->save(array(
$this->alias => array(
'agg_domain_id' => $domain_id,
'order' => $order,
'url' => $url
)
));
return (bool)$result;
}
From php.net:
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
So if you do if($this->queue('url',0)) then the cast is not necessary.
But if you do if($this->queue('url',0) === true) then you need to cast. And casting with (bool) is absolute legitimate.
Is this a valid way to cast something to boolean?
Yes
It's fine to do that where you only want to know success or fail.
When it's not ok
The only potential problems with casting the return value like that, is if the return value could be a falsey type e.g.:
array()
0
""
" "
a call to save always returns a nested array or false - there is no scope for getting a false-negative result with a call to save.