<?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 :-)
Related
here is my example:
$data = null;
var_dump($data); // returns null
is($data['test']);
var_dump($data); // returns array (size=1)
// 'test' => null
function is(&$var, $default = null)
{
return isset($var) ? $var : $default;
}
notice that after I run is($data['test']), $data becomes $data['test'] = null
any ideas why this behavior?
I am looking to get null. I am running php 7
edit: it's the & symbol, just not sure why would yield that result
You cannot pass a variable with a non existing key to a function (even with reference) since the value will be passed to the function.
If we have $data and in the next line if we do $data['test'], the $data variable will be updated to an array.
So in your case, when you use is($data['test']);, it updates the variable.
Then it goes to the function, and checks isset($var). It is already set since the variable is updated already. So the isset gets a true return. That return will contain the updated variable which is $data['test'].
I think the solution from #Fred B will work in this case.
try using array_key_exists() and return null if key not found.
This solution seems to work, though less elegant:
is($data, 'test');
var_dump($data); // returns array (size=1)
// 'test' => null
function is($var, $key, $default = null)
{
return isset($var[$key]) ? $var[$key] : $default;
}
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');
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');
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;
I'm curious to know if the following behaviour in PHP is intended or not. And, if it is intended, it is considered acceptable to initialize an array from a null variable by creating an index into it (as is done in the first code snippet)?
error_reporting(E_ALL);
$arr = null;
echo ($arr["blah"]===null) ? "null" : $arr["blah"];
$arr["blah"] = "somevalue";
echo "<br>";
echo ($arr["blah"]===null) ? "null" : $arr["blah"];
var_dump ($arr);
This outputs
null
somevalue
array (size=1)
'blah' => string 'somevalue' (length=9)
However, if the array is initialized first (see code below), I get the exact same output, but an "Undefined Index" notice is given when I first try $arr["blah"]
error_reporting(E_ALL);
$arr = array();
echo ($arr["blah"]===null) ? "null" : $arr["blah"];
$arr["blah"] = "somevalue";
echo "<br>";
echo ($arr["blah"]===null) ? "null" : $arr["blah"];
var_dump ($arr);
PHP won't attempt the comparison if the array is null.
In the second circumstance, a comparison does occur because the array is set. PHP does not check to see if it is empty.
Your ternary is attempting to access the variable $arr["blah"], not checking to see if it is set before doing a comparison.
The proper way to write this would be:
error_reporting(E_ALL);
$arr = array();
if(isset($arr["blah"])) echo ($arr["blah"]===null) ? "null" : $arr["blah"];
$arr["blah"] = "somevalue";
echo "<br>";
if(isset($arr["blah"])) echo ($arr["blah"]===null) ? "null" : $arr["blah"];
var_dump ($arr);
Actually, John Vargo was correct. If a variable is null, accessing it as if it were an array will simply return null without notices. This will change in the upcoming 7.4 version, then it will produce a notice.
Notice: Trying to access array offset on value of type null
The actual output is still the same.