We've got variable that for some reason we think would be an array, but it happens to be null.
$var = null
We try to get a value from this variable.
$value = $var['key']
This doesn't throw an error, my intuition is that it would though. What instead happens is that $value is now also null. Is there a particular reason that the above line doesn't throw an error?
There is "almost duplicate": Why does accessing array index on boolean value does not raise any kind of error?
the code there looks like:
$var = false;
$value = $var['key'];
and the answer is - it's just document
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.
So in this string (I am talking about your case, $var = null, but with boolean would be the same explanation, just replace NULL to boolean)
$var['key']
$var is the variable of type NULL, and accessing variable of type NULL (other type that array or object) using [] silently returns NULL.
You can use this kind of fallback
function _get($from, $key)
{
if(is_null($from))
{
trigger_error('Trying to get value of null');
return null;
}
return $from[$key];
}
Change
$value = $var['key'];
to
$value = _get($var, 'key');
Related
Very simple question as the title says.
I want PHP to behave rather than give me a error, it might just return another null to me when I called a method on a null object.
PHP on elsewhere looks like it doesn't care anything.
It returns null if you get a non-existed key from a array:
$foo = ['foo'=>'foo'];
var_dump($foo['bar']);
It returns null even if the array is null:
$foo = null;
var_dump($foo['bar']);
But it suddenly becomes serious to an object!
You should check the error, without saying that disable the report.
if ($foo != null) {
var_dump($foo['bar']);
}
// or
if(isset($foo['bar'])) {
var_dump($foo['bar']);
}
We've got variable that for some reason we think would be an array, but it happens to be null.
$var = null
We try to get a value from this variable.
$value = $var['key']
This doesn't throw an error, my intuition is that it would though. What instead happens is that $value is now also null. Is there a particular reason that the above line doesn't throw an error?
There is "almost duplicate": Why does accessing array index on boolean value does not raise any kind of error?
the code there looks like:
$var = false;
$value = $var['key'];
and the answer is - it's just document
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.
So in this string (I am talking about your case, $var = null, but with boolean would be the same explanation, just replace NULL to boolean)
$var['key']
$var is the variable of type NULL, and accessing variable of type NULL (other type that array or object) using [] silently returns NULL.
You can use this kind of fallback
function _get($from, $key)
{
if(is_null($from))
{
trigger_error('Trying to get value of null');
return null;
}
return $from[$key];
}
Change
$value = $var['key'];
to
$value = _get($var, 'key');
discussing with a friend of my work, we discover something weird about PHP. Let's get the following code:
<?php
$leo = false;
$retorno = $leo[0];
var_dump($retorno);
The return of var_dump() is NULL. Now, the thing is, why is returning NULL, if we are trying to access a bool as array?
The correct behavior isn't throw an exception telling us, that we are trying to access a non-array object as array (in this case a boolean var)?
what you guys think about that?
Since you are trying to access not a string, but a boolean it returns NULL. As from the manual:
Note:
Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.
It's NULL because $leo[0] isn't $leo. You haven't assigned the bool or string to $leo[0], therefore it's empty, and ultimately results in being NULL.
If you were to put:
$retorno = $leo;
Or
$leo[0] = false;
Then you would get the result you are expecting.
$leo = false;
$retorno = array($leo);
var_dump($retorno[0]);
Try this
Can you use the Ternary Operator in PHP without the closing 'else' statement? I've tried it and it's returning errors. Google search isn't yielding anything, so I think the answer is probably no. I just wanted to double check here. For instance:
if ( isset($testing) {
$new_variable = $testing;
}
Will only set $new_variable if $testing exists. Now I can do
$new_variable = (isset($testing) ? $testing : "");
but that returns an empty variable for $new_variable if $testing isn't set. I don't want an empty variable if it's not set, I want the $new_variable to not be created.
I tried
$new_variable = (isset($testing) ? $testing);
and it returned errors. I also tried
$new_variable = (isset($testing) ? $testing : );
and it also returned errors. Is there a way to use the Ternary Operator without the attached else statement, or am I stuck writing it out longhand?
EDIT: Following Rizier123's advice, I tried setting the 'else' part of the equation to NULL, but it still ends up appending a key to an array. The value isn't there, but the key is, which messes up my plans. Please allow me to explain further.
The code is going to take a bunch of $_POST variables from a form and use them for parameters in a stdClass which is then used for API method calls. Some of form variables will not exist, as they all get applied to the same variable for the API call, but the user can only select one. As an example, maybe you can select 3 items, whichever item you select gets passed to the stdClass and the other 2 don't exist.
I tried this:
$yes_this_test = "IDK";
$setforsure = "for sure";
$list = new stdClass;
$list->DefinitelySet = $setforsure;
$list->MaybeSet = (isset($yes_this_test) ? $yes_this_test : NULL);
$list->MaybeSet = (isset($testing) ? $testing : NULL);
print_r($list);
But obviously MaybeSet gets set to NULL because (isset($testing) comes after (isset($yes_this_test) and it returns
stdClass Object ( [DefinitelySet] => for sure [MaybeSet] => )
I won't know what order the $_POST variables are coming in, so I can't really structure it in such a way to make sure the list gets processed in the correct order.
Now I know I can do something like
if ( isset($yes_this_test ) {
$list->MaybeSet = $yes_this_test;
}
elseif ( isset($testing) ) {
$list->MaybeSet = $testing;
}
But I was hoping there was a shorthand for this type of logic, as I have to write dozens of these. Is there an operator similar to the Ternary Operator used for if/elseif statements?
Since PHP 5.3 you can do this:
!isset($testing) ?: $new_variable = $testing;
As you can see, it only uses the part if the condition is false, so you have to negate the isset expression.
UPDATE
Since PHP 7.0 you can do this:
$new_variable = $testing ?? null;
As you can see, it returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
UPDATE
Since PHP 7.4 you can do this:
$new_variable ??= $testing;
It leaves $new_variable alone if it isset and assigns $testing to it otherwise.
Just set it to NULL like this:
$new_variable = (isset($testing) ? $testing : NULL);
The you variable would return false with a isset() check.
You can read more about NULL in the manual.
And a quote from there:
The special NULL value represents a variable with no value. NULL is the only possible value of type null.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
Since PHP 7.0 you can do the following, without getting an ErrorException "Trying to get property 'roomNumber' of non-object":
$house = new House();
$nr = $house->tenthFloor->roomNumbers ?? 0
Assuming the property "tenthFloor" does not exist in the Class "House", the code above will not throw an Error.
Whereas the code below will throw an ErrorException:
$nr = $house->tenthFloor->roomNumbers ? $house->tenthFloor->roomNumbers : 0
You can also do this (short form):
isset($testing) ? $new_variable = $testing : NULL;
JUST USE NULL TO SKIP STATEMENTS WHEN IT WRITTEN IN SHORTHAND
$a == $b? $a = 20 : NULL;
<?php
ini_set('display_errors',1);
ini_set('error_reporting',-1);
$data = null;
var_export( $data['name']);
echo PHP_EOL;
var_dump($data['name']);
Why the result is null, but no notice or warning occured?
Because null is an undefined type, $data['name'] therefore creates its own array.
If you check the data type of $data before assigning null, you will get the undefined variable notice.
echo gettype($data);
$data = null;
After you assigned null to $data, you will see NULL for its value and its data type.
$data = null;
echo gettype($data);
var_dump($data);
According to the documentation of NULL, you're getting NULL for $data['name'] means that it has not been set to any value yet.
The special NULL value represents a variable with no value. NULL is
the only possible value of type null.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
The following two examples show that the previously defined variable is not auto-converting to array, and keep its original data type.
Example 1:
$data = null; // $data is null
var_dump($data['name']); // null
var_dump($data[0]); // null
Example 2:
$data = 'far'; // $data is string
$data[0] = 'b'; // $data is still string
echo $data; // bar
Just reread documentation about type casting in php.
http://php.net/manual/en/language.types.type-juggling.php
PHP is not so strict as c/c++ or java :-)