when does php json_decode return false? - php

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

Related

Laravel: Passing a value of 0 back to controller from frontend

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)) {

Function returning only FALSE

I have a php function.
if ( $this->input->post('email') == $this->_email($this->input->post('email')) )
{
$this->_data['error'] = 'Email exist!';
return $this->load->view('login/template_view', $this->_data);
}
My function returning only FALSE, even if equality is true. I use debug to see if my function can returning TRUE.
bool(false) string(14) "alex#yahoo.com" object(stdClass)#25 (1) { ["email"]=> string(14) "alex#yahoo.com" }
I have 2 strings, first is returning alex#yahoo.com, and 2nd string is returning alex#yahoo.com... but if condition still returning FALSE.
What is wrong in my function?
Debug:
var_dump($this->input->post('email'));
var_dump($this->_email($this->input->post('email')));
die();
You are comparing a string to an object. In order for your comparison to work, you need to compare the string against the email property of the object. You can access a object property by using -> or by using a method.
You can read more about PHP objects here and here.
In order for your code to work, replace:
if ( $this->input->post('email') == $this->_email($this->input->post('email')) )
with
if ( $this->input->post('email') == $this->_email($this->input->post('email'))->email )

Boolean result of the nested boolean values

I'm modelling an access function that should return boolean value based on next structure on nested array, which contains only boolean values:
based on dimension, comparison of the should be made either OR or AND type
first level is OR, next level is AND, next level is OR and so on
final result should return TRUE or FALSE
For example I have these arrays with expected results:
array(TRUE) -> TRUE
array(FALSE) -> FALSE
evidently...
array(TRUE, FALSE) -> TRUE
because of TRUE | FALSE
array(TRUE, array(FALSE)) -> TRUE
because of TRUE | (FALSE)
array(FALSE, array(FALSE, TRUE)) -> FALSE
because of FALSE | (FALSE && TRUE)
array(FALSE, array(TRUE, array(FALSE, TRUE))) -> TRUE
because of FALSE | (TRUE && (FALSE | TRUE))
What I'm doing here is just changing comparison method on every other level of the nested array.
PHP language example would be nice, but any prototype that I can transfer to PHP is accepted as an answer.
This is an example of mutual-recursion, using the array_reduce function
do_or applies the OR operator on the entire array
do_and applies the AND operator on the entire array
if an element of the array is an array itself, the functions apply each other
The Code:
function do_or($x,$y)
{
if (is_array($y))
{
if (empty($y))
{$y=FALSE;}
else
{$y=array_reduce($y,"do_and",TRUE);}
}
return $x||$y;
}
function do_and($x,$y)
{
if (is_array($y))
{
if (empty($y))
{$y=TRUE;}
else
{$y=array_reduce($y,"do_or",FALSE);}
}
return $x && $y;
}
$answer=array_reduce($arr,"do_or",FALSE);
This code could be optimized, but I guess it illustrates the idea

Is this simple cast safe when saving records?

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.

Value of option arguments: FALSE or NULL

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.

Categories