php undefined index notice not raised when indexing null variable - php

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.

Related

isset() or empty() statements not giving desired results

I am using the following code which is giving the same result irrespective of the condition;
foreach($data as $row)
{
$a = $row['name']; //Here I am calling name from an api
if(empty($a))
{
$a = 'AAA'; // Checking if a$ = $row['']; i.e. 'name' does not exist
}
echo $a;
}
The problem is when $row['name'] has value, it is getting echoed via $a, but if $row['name'] does not exist, I am getting error as undefined index: (probably for since 'name' is not available for that row.)
How to get $a echoed as 'AAA' in case $row['name'] does not exist?
Try checking the actual array and not the declaration of the null.
if(!isset($row['name']))
$a = "AAAA";
https://ideone.com/RuqOBs
The difference is subtle but important :
isset — Determine if a variable is set and is not NULL
empty — Determine whether a variable is empty
is_null — Finds whether a variable is NULL
write the else part like this :
foreach($data as $row){
if(empty($row['name']) || ! isset($row['name']) )
{
$a = 'AAA';}
}
else
{
$a = $row['name'];
}
echo $a;
}
isset() checks if a variable has a value including ( False , 0 , or empty string) , but not NULL. Returns TRUE if var exists; FALSE otherwise.
On the other hand the empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.
Check to see if name is set before doing your test and combine then into a single statement.
$a = (isset($row['name']) ? $row['name'] : 'AAA');
echo $a;
There are three functions to choose from, which have the following differences:
array_key_exists($key, $array)
This will check if the key exists in the array. If it does, no matter what value is stored behind it (even null), it will return true, false oterhwise.
isset($array[$key])
This will check if the key in the array exists and if the value behind it is not null. If it exists and is not null it will return true, false oterhwise.
empty($array[$key])
This will check if the key exists and if the value behind it is falsy. If it does not exist or the value is falsy (For example null, false, '' or 0) it will return true, false otherwise.
All those functions have in common, that you call them on the array directly. For you, you could call it like this:
foreach($data as $row) {
echo array_key_exists('name', $row) ? $row['name'] : 'AAA';
}
You can exchange array_key_exists('name', $row) with any of the other two functions, depending of what kind of behavior you want.

Why the 'NULL' value of a variable is not displayed using echo and print but displayed with var_dump() function?

As we all know if a variable is created without a value, it is automatically assigned a value of NULL.
I have following code snippets :
<?php
$name;
echo $name;
?>
AND
<?php
$name;
print $name;
?>
Both of the above code snippets' output is as below(it's exactly the same) :
Notice: Undefined variable: name in C:\xampp\htdocs\php_playground\demo.php on line 7
I have another code snippet :
<?php
$name;
var_dump($name);
?>
The output of above(last) code snippet is as below :
Notice: Undefined variable: name in C:\xampp\htdocs\php_playground\demo.php on line 8
NULL
So, my question is why the value "NULL" is not getting displayed when I tried to show it using echo and print?
However, the "NULL" value gets displayed when I tried to show it using var_dump() function.
Why this is happening?
What's behind this behavior?
Thank You.
The problem you're having is that NULL isn't anything - it's the absence of a value.
When you try to echo or print it, you get the notice about an Undefined Variable because the value of $name is not set to anything, and you can't echo the absence of something.
$name;
var_dump($name);
The output of this will be NULL to tell you that the variable had no value. It's not a string with the value of "NULL", it's just NULL, nothing, the absence of something.
Compare this to the following:
$name = '';
var_dump($name);
This outputs string(0)"" - this is telling you that $name DID have a value, which was a string which contained no characters ("") totalling a length of 0.
Finally, look at the following:
$name = 'test';
var_dump($name);
This outputs string(4)"test" - a string containing test, which had a length of 4

Using Ternary Operator without the Else statement PHP

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;

use php NULL like array

<?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 :-)

if array undefined

How do I check if an array is undefined?
I am using isset and empty but both of them are not working for an undefined array.
This is my code:
if (isset($content['menu']['main'])){
echo 'there is menu';
}
use this code as specified by Rikesh and mimipc
$arr = array("menu"=>array("main"=>1));
if (is_array($arr) && array_key_exists('menu', $arr)) {
echo "array";
}
working example http://codepad.viper-7.com/Q3gTwn
Based on your code, I think you're looking for the function array_key_exists().
$content = array('menu'=>array());
echo isset($content);
>>> 1
echo array_key_exists('menu', $content);
>>> 1
if ( array_key_exists('main', $content['menu']) ) {
echo "Main menu exists";
} else {
echo "Main menu does not exist";
}
>>> Main menu does not exist
isset() will not work, because the variable $content is set, and the array may not be empty, so empty() will also not work. You want to see if the main key exists in the $content['menu'] array.
You can check if an array element exists with in_array:
in_array('one', array('two', 'three', 'four')); // false
And you can check array-indexes with array_key_exists:
array_key_exists('metallica', array('metallica' => 'worst than megadeth')); // true
With the isset function you only check if the array or variable is not equal to NULL and if it contains a value which can be interpreted as boolean True or False, integers larger than 0 and if the variable value (or array key/index/element) is not equal to NULL.
I usualy check if variable is set with: is_null, and it can be used to check if an array index or an element is defined within that same array.
EDIT:
You can also check if a variable is array with: (sizeof($something) > 0) or with: is_array function(s).

Categories