Why should Null value exist PHP? - php

I find it's really hard to understand the Null datatype in PHP. Why does it even need to exist? If it's only represent an empty value why PHP doesn't just offer a way to remove it from the code since the variable contains it doesn't have any useful thing to do in our application?

Consider this:
if (some_condition) $var1 = "Bob";
Now if that condition is false, then $var1 would be null because you did not define it. So, you could have the decision to check if it is null to proceed with what you want to do with it.
if (!is_null($var1)) {
// do something
}
Hope that helps.

Related

What does this code actually do?

I have recently been employed at an office where they use a lot of php in their work, most of my development background is HTML, CSS, Jquery, Wordpress and Angularjs, I have an idea behind the logic of some of php but was just wondering if anyone can enlighten me as to what this code below actually means/does?
return (isset($rs[0][0]) ? $rs[0][0] : "");
It is located within this function that calls the database and returns values.
function get_temp($table, $field){
global $db;
$sql="select $field from $table";
$rs=$db->select($sql);
return (isset($rs[0][0]) ? $rs[0][0] : "");
}
I feel that is selecting one value from an array within an array but I cannot find any sources to confirm this so was hoping someone on here could help me out or at least point me in the right direction if I am wrong. The reason I believe this is the case is because if I pass the $field variable more than one result it will always only return the first one, if this is the case it would also be helpful to me if someone could suggest a way to get all of the results, whenever I simply try:
return $rs
It simply returns "Array".
(isset($rs[0][0]) ? $rs[0][0] : "");
This is a ternary operator. It does a check if $rs[0][0] is set. If yes it will make the function return $rs[0][0]'s value, if not it will return an empty string.
You could translate it to an if statement like this:
if (isset($rs[0][0])) {
return $rs[0][0];
}
return "";
In fact the method isset will check is the value is null.
Then it is simply a ternary operator, returning the value of the variable if it is not empty and an empty string if the value of the var is empty.

What is the proper way of checking a table key existence before using its value?

I want to check if $table['key'] exists before using it. What is the proper way of doing this?
I've seen a lot of different codes, but I do not know if they are all equivalent and right. Here are a few examples :
// 1
if(isset($table['key'])) { ... }
// 2
if(isset($table) and isset($table['key'])) { ... }
// 3
if(isset($table) and array_key_exists('key',$table)) { ... }
if (isset($table['key']))
Yes.
if (isset($table) and isset($table['key']))
That's redundant, there's no advantage to checking both individually.
if (isset($table) and array_key_exists('key', $table))
Yes, this is also a good method if $table['key'] may hold a null value and you're still interested in it. isset($table['key']) will return false if the value is null, even if it exists. You can distinguish between those two cases using array_key_exists.
Having said that, isset($table) is not something you should ever be doing, since you should be in control of declaring $table beforehand. In other words, it's inconceivable that $table may not exist except in error, so you shouldn't be checking for its existence. Just if (array_key_exists('key', $table)) should be enough.
The rule of thumb I personally apply:
If the value that corresponds with the key may be null:
If $table may not exist, use isset($table) && array_key_exists('key', $table).
Otherwise, use array_key_exists('key', $table).
In all other cases, use isset($table['key']).
In the cases of 1.1 and 1.2, it's technically possible that $table is not an array; in that case you would need to add is_array($table) as well ... but if it ever gets this far, something else is wrong imho.

What is the difference between null and empty?

I am new to the concept of empty and null. Whilst I have endeavoured to understand the difference between them, I am more confused. I came across an article at http://www.tutorialarena.com/blog/php-isset-vs-empty.php however I still don't see when you would use isset and empty when validating forms. Seeing that I don't grasp the difference, I don't want to be using the incorrect functions as well as not be able to use the functions in other areas. Can someone give examples that will help me understand? I am very new to coding so would appreciate if someone could give me real world examples and at the same time keep it simply enough for noob to follow.
A variable is NULL if it has no value, and points to nowhere in memory.
empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL.
The following things are considered to
be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Source.
Example
$a is NULL.
$a = '' is empty, but not NULL.
Update
If $a='' is empty but not NULL, when do I use the empty() function and when do I use the isset() function.
isset() will return FALSE is the variable is pointing to NULL.
Use empty() when you understand what is empty (look at the list above).
Also when you say it points nowhere in memory, what does that mean exactly?
It means that $str = '' will be in memory as a string with length of 0.
If it were $str = NULL, it would not occupy any memory.
Null is a placeholder that generally means "no data about this is available".
The use of null for this is just a convention, but a rather widespread one, to the point where some programming languages support the convention directly. The reason this convention exists has IMHO historically to do with "pointers";
many times a procedure will be defined to return a pointer to an answer, and will return what is traditionally called a Null pointer if it could not produce an answer for some reason.
Empty means (if this is a set) that it has no members. That's an explicit answer, and it is very different than "no data about this is available".
In the PHP world, apparantly uninitialized variables have the Null value, and isset on such a variable returns FALSE.
For arrays and strings, PHP follows the convention that "empty" means "has no members" although arrays and strings are not technically sets.
PHP apparantly has this funny idea that 0 and 0.0 are also "empty", by PHP design. That's abusive of the concept of "empty" IMHO: Individual numbers are not sets, so 0 can't reasonably by "empty". THis just leads to obscure programming because it violates the principle of least surprise. I'm sure the PHP designers would are that "zero is the empty number" as some kind of vague analogy; but the if analogy is vague, why bother with it? But then PHP is full of silly ideas.
The table below is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool(false).
refer this link for more https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
NULL is a special value which explicitly states that the variable has not been set to any value yet. Be careful with using the empty() function as you can't just determine that a variable is exactly NULL using it. For example the empty() function will return true if an int is set to 0. If you need to make sure a variable is exactly NULL use if($variable == NULL).
For more info on empty() see http://php.net/manual/en/function.empty.php
There are some good answers here, which I won't repeat. In the case of validating forms, though, when a form is submitted, the value of each form input element is sent to the server in the $_POST variable. You can check for the existence of a particular input by using isset().
isset($_POST['username'])
If this returns true, then this request to the server was the result of posting a form containing an input element named "username". Now that we know that we have a value for that form element, we can see if it has a valid value. empty() will tell us whether the user actually entered any data in the field, or whether they left it empty.
empty($_POST['username'])
If that returns true then the form submitted to the server had a field named "username" but the user didn't enter anything into before submitting the form.
Been awhile since i used PHP but if other languages are anything to go by empty will indicate an existing object/map/array that has no contents while null would indicate a variable that has no meaning/definition at all (uninitialised).
In database SQL, NULL means "no value".
The empty() is a nice fast way to see if the variable holds any useful info... that is for strings empty() returns true for a string of "" as well as a null string.
So you can write something like this:
if (! empty($name)) echo $name;
More info see here: PHP: empty()
isset() returns true if both these conditions are met:
The variable has been defined and has not yet been unset.
The variable has a non-null value in it.
A variable is automatically defined when it gets set to something (including null). This has a direct implication in arrays.
$a=array();
$a['randomKey']=true;
$a['nullKey']=null;
var_dump(isset($a['randomKey'])); // true
var_dump(isset($a['nullKey'])); // true, the key has been set, set to null!
var_dump(isset($a['unsetKey'])); // false !
unset($a['randomKey']);
var_dump(isset($a['randomKey'])); // false ! it's been unset!
From above, you can check if various $_POST fields have been set. For example, a page that has been posted to, stands to reason, has the submit button name in the $_POST field.
empty() on the other hand, tests if the variable holds a non zero value. This means that values that (int) cast to 0, return false too. You can use this to see if a specific $_POST field has data in it.
This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).
Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.
In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null. The second example is akin to empty.

PHP: why is this null different from the other null

hi i tried 2 things what should be the same however it my testing says different does anyone know why the only thing i do is put it in a variable...
if ($_SESSION[$something] === null)
echo("this is null");
$_SESSION[$something] does not exists so it indeed says: "this is null".
now look at this
$theSession = $_SESSION[$something];
if ($theSession === null)
echo("this is null");
now it does not say "this is null" while it should be exactly the same right?
You need a $ in front of theSession in the second block of code.
You do may not need the $ in front of something. You only need it if $something is holding a string of the session variable name. Otherwise if something is the session variable name you dont need the $.
You should also consider using is_null to check is a variable contains a null value.

In PHP, what is the differences between NULL and setting a string to equal 2 single quotes

I used to set things like this when I wanted blank values.
$blankVar = '';
Then after some months, I decided this looked better and had a clearer intent.
$blankVar = null;
This worked without hiccup for a while, but recently with a PDO prepared statements I ran into a problem. Binding a value to null made the query fail, whilst binding it to '' did not. I needed to bind it to null, so that if a condition was met, it would insert blank data.
What are the differences between the 2? I still think equaling null (or at least a constant) looks better, so should I do this?
define('EMPTY', '');
Null is just another datatype in PHP, which has only one value (null). Since PHP is a loosly typed language, it can be confusing how it handles different values.
"", 0, "0", False, array(), Null are all considered False in PHP.
Null, however, is a different kind of animal. The main incompatibility with using Null is that you cannot tell if it isset().
$x = false;
isset($x) -> true
echo $x -> ""
$y = null;
isset($y) -> false
echo $y -> ""
//$z is not set
isset($z) -> false
echo $z -> E_NOTICE
So null is odd in the sense that it doesn't follow normal variable rules in PHP (at least some). In most cases, it is fine.
When it comes to database columns, PHP's NULL has no place there. You see, SQL is a string based language. SQL's NULL must be represented by NULL with no quotes.
So if you want an EMPTY field, set it to ""
INSERT INTO foo SET bar = ""
But if you want a NULL field, set it to NULL
INSERT INTO foo SET bar = NULL
BIG DIFFERENCE.
But if you try to insert the PHP NULL directly, it will add zero characters to the query, (which leaves you with a blank or syntax error, depending on if you quoted it).
null is a special placeholder value in the programming language that literally means "nothing". It's not 0, it's not an empty string, it's nothing. There is no value in memory being pointed to. An empty string, on the other hand, is still a string object, just a very short one :)
Well, it's one thing how nice each approach looks, but the main difference is that one is an empty string and the other is an uninitialized variable (null)
Aside from the differences stated by Rex, there's two types of comparisons in PHP, loose and strict:
http://www.php.net/manual/en/types.comparisons.php
If strict comparisons or functions like is_null() are used in any capacity, you'll get different results. With loose comparisons, however, PHP is pretty lenient.
I don't know for sure, but you may be able to use your null approach, then just typecast when you're using the variable in the context where you had issues (i.e. pass (string) $blankVar). If that works, it may mean less changes are necessary to your code.
'null' is the unique thing that uninitialized variables refer to. You can set a variable to refer to null. There is also the 'unset' state meaning the variable doesn't exist at all. You can check that via the isset() function. Most often used to check if an element of array exists and is, for example, a way to see if $_GET['op'] has received a querystring param. You can also make a variable unset (remove an element of an array) via the unset() function. There is also a function empty() which will check if a variable is either NULL, FALSE, 0, or an empty string

Categories