What is my error in the very simple php? - php

i make a very simple php to check a data, but it not works.
<?php
$ngl="G";
if ($parsed[0][4]="0") {
$ngl="NG";
}
if ($parsed[0][5]="0") {
$ngl="NG";
}
?>
and the output of the
<?php echo $ngl; ?>
is always
G
But I know that $parsed[0][4] and $parsed[0][5] is 0. The problem is that the output is G and not NG! I also tried to remove $ngl="G"; but then the output is nothing.
What do I have to repair?
i just use = but == its the correct. thx all.

You're assigning (=) a value instead of comparing (== or ===)
<?php
$ngl = "G";
if($parsed[0][4] == "0")
{
$ngl = "NG";
}
if($parsed[0][5] == "0")
{
$ngl = "NG";
}
?>
Explanation:
When you put an assignment like $parsed[0][4]="0" in an if statement, the if will evaluate the "0" to false. The reason it evaluates just the "0" is because the line $parsed[0][4]="0" (any assignment) returns the right hand side of the operation (the "0")
== vs === : php.net - Comparison Operators
== is a loose comparison which doesn't compare the type. ie "2" == 2 is true (even though one is a string and the other is an integer)
=== is a strict comparison, comparing types as well as values. ie "2" === 2 is false
The if statement uses the former (loose) comparison on your "0", and of course 0 is the false value in binary (0 and 1), so 0 == false and "0" == false both evaluate to true - however, 0 === false would return false as 0 is an integer, whereas false is a boolean.

Use == not = when checking
<?php
$ngl="G";
if ($parsed[0][4]=="0") {
$ngl="NG";
}
if ($parsed[0][5]=="0") {
$ngl="NG";
}
?>

You use = to set variables. You use == to compare.
<?php
$ngl="G";
if ($parsed[0][4]=="0") {
$ngl="NG";
}
if ($parsed[0][5]=="0") {
$ngl="NG";
}
?>

You should use == rather than =:
<?php
$ngl="G";
if ($parsed[0][4]=="0") {
$ngl="NG";
}
if ($parsed[0][5]=="0") {
$ngl="NG";
}
?>
The reason is that the = is the assignment operator, while the == is the comparison operator (which is the one you want).
$parsed[0][4]=="0" will evaluate to 0, which is false, so $ngl will not be changed. The same thing happens with $parsed[0][5]=="0"

This line is not checking if $parsed[0][4] is zero. It makes it zero.
if ($parsed[0][4]="0") {
Change it to
if ($parsed[0][4]=="0") {

Related

If statement is true OR not false [duplicate]

This question already has answers here:
Is there a difference between !== and != in PHP?
(7 answers)
difference between != and !== [duplicate]
(4 answers)
The 3 different equals
(5 answers)
Closed 3 years ago.
I have two statements like this:
$ready = true;
if($ready === true) {
echo "it's ready!";
}
And this:
$ready = true;
if($ready !== false) {
echo "it's ready!";
}
I know those mean the same thing as === true and !== false is the same thing. I see people use the negation type (is not false or is not {something}). like this: https://stackoverflow.com/a/4366748/4357238
But what are the pros and cons of using one or the other? Are there any performance benefits? Any coding benefits? I would think it is confusing to use the negation type rather than the straight forward === true. Any input would be appreciated! thank you
These do not mean the same thing, and you can see this demonstrated below:
$ready = undefined;
if($ready === true) {
console.log("it's ready 1");
}
if($ready !== false) {
console.log("it's ready 2");
}
When in doubt, stick with ===. You're comparing to exactly what it should be. "This should exactly be equal to true" vs "This should be equal to anything but exactly false" are 2 separate statements, the second including a lot of values that would be true (As demonstrated above, undefined is not exactly false, so this would be true).
Most PHP functions return false as failure, such as strpos, from the manual it says:
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So it returns an integer or false, then it is wrong to use strpos() === true
strpos() !== false is the right way to check the result.
It is not about performance and they are not the same. It helps us in reducing unnecessary if else statements.
Consider this: there is a variable foobarbaz whose value can be anything among foo/ bar/ baz/ foobar/ barbaz. You need to execute a statement if the value is not foo. So instead of writing like this:
if(foobarbaz === "bar" || foobarbaz === "baz" || foobarbaz === "foobar" || foobarbaz === "barbaz") {
//some statement
}
else if(foobarbaz === "foo") {
//do nothing
}
You can write something like this:
if(foobarbaz !== "foo") {
//some statement
}
You can see we were able to eliminate the unnecessary else statement.
In php == compare only the values are equal. For and example
$ready = 'true';
if($ready == true) {
echo "true";
}
else{
echo "false";
}
It print true.But if it is compare with === it not only check the values but also it check the datatype. So it compares with === it print the false.
Talking about !== it's work as the same. So it's not a problem to output if you use
if($ready === true)
or
if($ready !== false)
Can't compare these two because both are same.

False converted to null automatically in my PHP

I'm new to PHP and I found in my code, when I pass a FALSE to a function. It converted to null immediately. I've read some articles knowing that False and null are equal. But I don't know when this conversion happens.
Below is my code
function equal($expected, $actual){
if($expected == $actual) { //... }
}
function foo(){
$signal = getSignal();
equal(FALSE, $signal->good); //...
}
You will need to use triple equal signs === for equality. For example
false == null; // true
false === null; // false
0 == false; // true
0 === false; // false
Check the docs on comparison operators
No, they are NOT converted. You can var_dump($variable) at any time to see both the type and the value of $variable any time. But there are a few things which evaluates to false with the == comparison operator. So in fact false == null will evaluate to true just as false == 0 or false == "0" in PHP. This is why the comparison operator === comes into the picture - using that instead of == in above example, all will evaluate to false instead of true.
For more information, see http://php.net/manual/en/language.operators.comparison.php

php variables comparison == vs ===

this is code:
$s = 0;
$d = "dd";
if ($s == $d) {
var_dump($s);
die(var_dump($d));
}
result is:
int 0
string 'dd' (length=2)
Please explain why.
why ($s == $d) results as true?
Of course, if === is used it will results as false but why this situation requires ===?
Shouldn't it be returned false in both situations?
Because (int)$d equals with 0 and 0=0
you must use strict comparison === for different character tyes (string) with (int)
Your $d is automatically converted to (int) to have something to compare.
When you compare a number to a string, the string is first type juggled into a number. In this case, dd ends up being juggled into 0 which means that it equates to true (0==0).
When you change the code to:
<?php
$s = 1;
$d = "dd";
if ($s == $d)
{
var_dump($s);
die(var_dump($d));
}
?>
You will find that it doesn't pass the if statement at all.
You can more details by reading up on comparison operators and type juggling.
The string "dd" is converted to int, and thus 0.
Another example :
if ( "3kids" == 3 )
{
return true;
}
And yes, this returns true because "3kids" is converted to 3.
=== does NOT auto convert the items to the same type.
Also : 0 == false is correct, but 0 === false is not.
See : http://php.net/manual/en/language.types.type-juggling.php
The string will try to parsed into a number, returns 0 if it is not in right number format.
As seen in the php website :
http://php.net/manual/en/language.operators.comparison.php
var_dump(0 == "a"); // 0 == 0 -> true
In PHP, == should be pronounce "Probably Equals".
When comparing with ==, PHP will juggle the file-types to try and find a match.
A string with no numbers in it, is evaluated to 0 when evaluated as an int.
Therefore they're equals.

RowCount() = 0 error php mysql

echo "<h2 style='margin:0; padding:0;'>Recent Comments</h2>";
if ($sth7->rowCount()) {
while($row7 = $sth7->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='comment'>{$row7['usr']} said";
}
}
else($sth7->rowCount() = 0)
echo "User";
Can't use method return value in write context
Why doesnt that rowcount() = 0 logic work?
= is the assignment operator in PHP.
You're basically trying to assign 0 to $sth7->rowCount().
Perhaps you mean $sth7->rowCount() == 0?
Also, you really don't need the if else if. It could be just an if else:
if($sth7->rowCount()) {
} else {
}
rowCount() returns an integer, and any integer except for 0 will cast to true.
Try rowcount() == 0 to compare with 0, your code (rowcount() = 0) tries to assign 0. Also, it's may be useful to put constant on the left side while comparing : (0 == rowcount()) to make such errors easier to detect.
else doesn't take any logic, it just runs if it's assosciated if (and any elseifs) didn't evaluate true.
Also, = is an assignment operator - read it as "becomes equal to"
$var = 1; // Var becomes equal to 1
== is an equality operator, it tests if two expressions are equal
$var == 1 // Var is equal to 1
You probably want
else if ($sth7->rowCount() == 0)
echo "User";

Does PHP have short-circuit evaluation?

Given the following code:
if (is_valid($string) && up_to_length($string) && file_exists($file))
{
......
}
If is_valid($string) returns false, does the php interpreter still check later conditions, like up_to_length($string)?
If so, then why does it do extra work when it doesn't have to?
Yes, the PHP interpreter is "lazy", meaning it will do the minimum number of comparisons possible to evaluate conditions.
If you want to verify that, try this:
function saySomething()
{
echo 'hi!';
return true;
}
if (false && saySomething())
{
echo 'statement evaluated to true';
}
Yes, it does. Here's a little trick that relies on short-circuit evaluation. Sometimes you might have a small if statement that you'd prefer to write as a ternary, e.g.:
if ($confirmed) {
$answer = 'Yes';
} else {
$answer = 'No';
}
Can be re-written as:
$answer = $confirmed ? 'Yes' : 'No';
But then what if the yes block also required some function to be run?
if ($confirmed) {
do_something();
$answer = 'Yes';
} else {
$answer = 'No';
}
Well, rewriting as ternary is still possible, because of short-circuit evaluation:
$answer = $confirmed && (do_something() || true) ? 'Yes' : 'No';
In this case the expression (do_something() || true) does nothing to alter the overall outcome of the ternary, but ensures that the ternary condition stays true, ignoring the return value of do_something().
Bitwise operators are & and |.
They always evaluate both operands.
Logical operators are AND, OR, &&, and ||.
All four operators only evaluate the right side if they need to.
AND and OR have lower precedence than && and ||. See example below.
From the PHP manual:
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;
In this example, e will be true and f will be false.
Based on my research now, PHP doesn't seem to have the same && short circuit operator as JavaScript.
I ran this test:
$one = true;
$two = 'Cabbage';
$test = $one && $two;
echo $test;
and PHP 7.0.8 returned 1, not Cabbage.
No, it doesn't anymore check the other conditions if the first condition isn't satisfied.
I've create my own short-circuit evaluation logic, unfortunately it's nothing like javascripts quick syntax, but perhaps this is a solution you might find useful:
$short_circuit_isset = function($var, $default_value = NULL) {
return (isset($var)) ? : $default_value;
};
$return_title = $short_circuit_isset( $_GET['returntitle'], 'God');
// Should return type 'String' value 'God', if get param is not set
I can not recall where I got the following logic from, but if you do the following;
(isset($var)) ? : $default_value;
You can skip having to write the true condition variable again, after the question mark, e.g:
(isset($super_long_var_name)) ? $super_long_var_name : $default_value;
As very important observation, when using the Ternary Operator this way, you'll notice that if a comparison is made it will just pass the value of that comparison, since there isn't just a single variable. E.g:
$num = 1;
$num2 = 2;
var_dump( ($num < $num2) ? : 'oh snap' );
// outputs bool 'true'
My choice: do not trust Short Circuit evaluation in PHP...
function saySomething()
{
print ('hi!');
return true;
}
if (1 || saySomething())
{
print('statement evaluated to true');
}
The second part in the condition 1 || saySomething() is irrelevant, because this will always return true. Unfortunately saySomething() is evaluated & executed.
Maybe I'm misunderstood the exact logic of short-circuiting expressions, but this doesn't look like "it will do the minimum number of comparisons possible" to me.
Moreover, it's not only a performance concern, if you do assignments inside comparisons or if you do something that makes a difference, other than just comparing stuff, you could end with different results.
Anyway... be careful.
Side note: If you want to avoid the lazy check and run every part of the condition, in that case you need to use the logical AND like this:
if (condition1 & condition2) {
echo "both true";
}
else {
echo "one or both false";
}
This is useful when you need for example call two functions even if the first one returned false.

Categories