PHP why (null === $variable) and not ($variable === null) in comparison? [duplicate] - php

This question already has answers here:
Is there any benefit of using null first in PHP?
(5 answers)
Closed 8 years ago.
When reading Symfony2 code I came across this comparaison many times
if (null === $variable ) { ... }
I use
if ($variable === null ){ ... }
because I see it more readable.
Is there a wisdom behind using the first notation ?

No compile/interpretting difference at all, it's pure code style.
It's also known as Yoda Conditions.

It helps prevent accidental assignments:
if ($foo = null) { ... }
would not cause a parse error, while will
if (null = $foo) { ... }
1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10
2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd

Not only does it help prevent accidental assignments, but also avoids confusion when we do intentionally want to make an assignment when evaluating a condition.
if (null !== $article = $repository->findOneById($request->query->get('id'))) {
$title = $article->getTitle();
//....
}

Related

Syntax understanding in Symfony cookbook [duplicate]

This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 7 years ago.
Could someone explain me the following line which is in the Symfony Cookbook (FYI the main topic is dynamic generation for Submitted Forms)
I don't undersand the following: ? , neither the array() :
$sport = $event->getData()->getSport(); // getdata submited by the user in the Sport input
$positions = null === $sport ? array() : $sport->getAvailablePositions();
// is it similaire to that line? what the difference?
$positions = $event->getData()->getSport()->getAvailablePositions();
? is a ternary if; which is an if statement on a single line.
It could be rewritten as
if (null === $sport) {
$positions = array(); // an empty array
} else {
$positions = $sport->getAvailablePositions();
}
The line says, if $sport is null (=== means check both type/value), $sport will be an empty array(), if not, $sport will be $sport->getAvailablePositions();
$positions just get the result of it!
This is called "Ternary Logic". You can check for a good article on this here: http://davidwalsh.name/php-shorthand-if-else-ternary-operators
The logic is:
Is $sport null?
If so, return an array
Otherwise, get the availablePosition collection
The goal is to have something iterable at the end and in all cases, like an array, a collection, etc.
It is not similar to $positions = $event->getData()->getSport()->getAvailablePositions(); because this will throw an error if getSport() returns null, thus calling getAvailablePosition() on something null.
It's a ternary condition operator. It's the factorisation of an if then followed by an affectation.Documentation

How to $_GET php variable in url [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have this PHP code and trying to get the value of the variable language from the url parameters when specified link is clicked.
How do I do this? The code below only gets the value of Java in the first statement and not the values in the elseif statements.
if (isset($_GET['language'])) {
if ($_GET['language'] = 'Java') {
$q = 'title:(Java+Developer)';
}
elseif ($_GET['language'] = 'PHP') {
$q = 'title:(PHP+Developer)';
}
elseif ($_GET['language'] = 'JavaScript') {
$q = 'title:(JavaScript+Developer)';
}
}
Links:
<li>Java</li>
<li>PHP</li>
<li>JavaScript</li>
There's a difference between = and ==. One is for assigning, the other for comparing.
In your first if() statement, you're assigning the value Java to $_GET['language'], which will evaluate to Java. This will then be true.
Change the single = in the comparisons to ==, and you should be all set.
You are using a single equals sign. This is an assignment (as you do when defining a variable).
You need to use double equals signs ==. This is how you test equality.
$_GET['language'] == SOME_STRING
In addition, I would recommend using a switch statement instead of multiple if statements:
if ( isset( $_GET[ 'language' ] ) ) {
switch( $_GET[ 'language' ] ){
case "Java":
$q = 'title:(Java+Developer)';
break;
case "PHP":
$q = 'title:(PHP+Developer)';
break;
case "JavaScript":
$q = 'title:(JavaScript+Developer)';
break;
}
}
Using a switch statement will make this code much easier to maintain and also to add extra conditions (other languages).
Check the equal sign! Replace "=" with "=="
try with this code
if (isset($_GET['language'])) {
if ($_GET['language'] == 'Java') {
$q = 'title:(Java+Developer)';
}
elseif ($_GET['language'] == 'PHP') {
$q = 'title:(PHP+Developer)';
}
elseif ($_GET['language'] == 'JavaScript') {
$q = 'title:(JavaScript+Developer)';
}
}
You are assigning value Java to $_GET["language"] which always returns true. You must compare the value of $_GET["language"] against a string. Compare using == or === operator.
if ($_GET["language"] === "Java") {
/* here be dragons */
}
It is also good habit to use Yoda Conditions to catch this kind of errors.
if ("Java" === $_GET["language"]) {
/* here be dragons */
}
You are using "=" here which is for assigning the variable some value.
Have a look at the use of these:
"=" is used for assigning a value to some variable.
"==" is used for comparison (regardless of the data type). For example if
$var =1 and we evaluate a condition
if($var == TRUE )
The result will be bool True because TRUE is 1 and FALSE is 0 always.
3.
"===" comparison based on datatype also. The above condition will evaluate to Bool False because the data types are different.
You should use == instead of =.

PHP Syntax: "or" in "If" Statement [duplicate]

This question already has answers here:
How to have multiple conditions on the same if statement? [duplicate]
(5 answers)
Closed 8 years ago.
hello I just wanted to check and see if this would be correct PHP syntax:
if ($input == "DeOnTRAY96#localhost"){
echo"
Projects: 1"?>
<br>
<?php
echo"
Admin: yes
";
}
elseif ($input == NULL){
die("Please enter password.");
}else{
header("Location:Invalidpassword.php");
exit;
}
Right where is says
if($input == "DeOnTRAY96#localhost"){
Could I put
if($input == "DeOnTRAY96#localhost" or "somethingelse"){
And still have it work?
You don't want
if($input == "DeOnTRAY96#localhost" or "somethingelse"){
You want
if($input == "DeOnTRAY96#localhost" or $input == "somethingelse"){
I might suggest using === instead of == in this case, as you'd like a type sensitive comparison.
Additionally, for $input == NULL you should use is_null($input). Null is weird in most programming languages, so language specific functions for testing are usually the way to go (rather than comparison)
OR syntax in PHP:
if($var == 'something' || $var == 'something else')
{
//do something
}
For reference:
|| means OR
&& means AND
For a more future-proof solution, consider in_array. I use it for as few as two options, if there's even the slightest chance there may be more added.
if( in_array($input, ["DeOnTRAY96#localhost", "somethingelse"]))
Once you get to four or more options, it's probably better to do something more like:
$whitelist = [
"DeOnTRAY96#localhost"
, "somethingelse"
, "anotheroption"
, "too many options to do inline!"
];
if( in_array($input, $whitelist))

Checking if a variable is null [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
is_null($x) vs $x === null in PHP
In the following context !== null, !is_null() and isset() all produce the same result:
$foo = null;
function foo() {
if ($this->foo !== null) {
...
}
if (!is_null($this->foo)) {
...
}
if (isset($this->foo)) {
...
}
}
Which one is the quickest and which would you recommend in that context?
If you're not sure that the variable exists, use isset.
Example:
$content = (isset($_POST['content'])) ? $_POST['content'] : null;
Otherwise, use strict comparison to null.
if ($content === null) { }
(Really, I'm just pushing my opinion on your with the strict comparison. I just think it looks better than is_null, and it's probably an extremely small bit faster.)
Use isset only if the variable may not be set. I.e. if you do not know whether the variable exists at this point or not. Since you do know that it should exist at this point, don't use isset.
The difference between !== null and !is_null is negligible and mostly depends on your preference. Personally, I like !== null.
if ($this->foo !== null) {
//...
}
I prefer this condition.
According to me
if($this->foo!=""){
//...
}
this is the quickest one and produce the result quickly

The usage of == and === in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does “===” mean?
I am confused with the use of those operators in php, I am not quite sure when should I use === and when ==.
for example why/when should I write:
if( $some_method_that_returns_something_or_false() === FALSE) {
//do stuff
}
and when with ==?
Also, does === means I must return bool FALSE or I can return 0? When it is considered an bad practice to use === or ==?
Also when putting something like this:
if($some_method_that_returns_true_or_false()) {
}
is that $some_method_that_returns_true_or_false() == TRUE or
some_method_that_returns_true_or_false() === TRUE?
=== means exact value, so for true it has to be true, while == checks for the meaning of the value, so true will be also a value of '1' or a whatever String.
== is used for checking equallity and === is used for checking the equality as well as type.
And
if($some_method_that_returns_true_or_false()) {
}
is checking for $some_method_that_returns_true_or_false() == TRUE

Categories