Variable assignment in a conditional? - php

What would this evaluate to? I know it looks funny but I was looking at a practice exam and saw this:
if (number = 1) { echo "C1 is true"; }

Whenever you are assigning variables it always returns true when the assigned variable is not causing false.So it will go to the if and echo the output.And consider that it mainly depends on the value that you are assigning.
Suppose if you do like
if (number = 0) { // if(number = false)
echo "C1 is true";
} else {
echo "C1 is false";
}
It will prints C1 is false.Bec it will indirectly indicate like
if(0) // if(false)
which is a false.

The assignment operator = returns the assigned value. What does that mean? For example, the + operator in 1 + 2 returns the sum of two numbers; the value of the expression 1 + 2 is 3. In the same vein, the value of the expression number = 1 is 1. That's why this works:
a = b = c = 1;
So you're assigning 1 to number, the resulting value of which is 1, which is evaluated by if, which equals true.

Related

Increase Value of Array Index?

I was Do some Testing on Arrays , but I saw something in my code :
$arr = array();
$arr[0]++;
echo $arr[0];
output = 1 ;
Why is index[0] value is 1 ?
From my code above I don't do an assignment like
$arr[0] = 1 ;
I think this is due to loose types in PHP.
null == false == 0
this means that $arr[0] (null before the ++) is loosely equal to 0. So null (or 0) + 1 = 1.
Because it interprets as $arr[0] = $arr[0] + 1 ;. If you try with var_dump($arr[0]), then you will see that var_dump($arr[0]); returns NULL so NULL + 1 is equal to 1(converts NULL to 0 internally) that's why it returns 1 at the end.
$arr = array();
$arr[0] = $arr[0] + 1 ;
echo $arr[0];
Also you should see a Notice like
Notice: Undefined offset: 0
$arr[0]++;
That expression is execured as:
$arr[0] = $arr[0] + 1;
but your array doesn't contain an element with zero index. That element isn't instantiated and that value is null. That expression can be written as:
$arr[0] = null + 1;
null value converted to integer and have 0 value automaticaly and the expression is executed as
$arr[0] = 0 + 1;
Not that it really matters, because the effect is the same, but there is no type juggling before the increment operation. Incrementing an undefined value directly results in 1. It is not converted to zero and then incremented.
The PHP manual explains this behavior. First, null:
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().
Next, Incrementing/Decrementing operators:
Note: The increment/decrement operators only affect numbers and strings. Arrays, objects, booleans and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.
So, $arr[0] is null because it has not been set to any value yet.
And incrementing null results in 1.
Use 1 of 3 examples:
<?php
$arr = array();
for ($i=0; $i < sizeof($arr)+1; $i++){
$arr[$i] = $i+1;
}
echo $arr[0]; //1
?>
<?php
$arr = array('0');
$arr[0]++;
echo $arr[0]; //1
?>
<?php
$arr[0] = 0;
echo $arr[0]++; //1
?>

How to apply if condition when it's parameter is coming into a variable?

I have assigned a condition into a variable. Then I tried to put that variable as a parameter of a if statement. But the code is not working. Please check my code:
$a = 8;
$final_str = '$a == 10';
if($final_str) {
echo 'Output 1';
} else {
echo 'Output 2';
}
The desired output should be Output 2. But it is not working. I always see Output 1. Please help me in this case.
Thanks in advance!
As per your request, the real problem here is this line of code:
$final_str = '$a == 10';
Although you have said that you cannot change the first two lines of code as it is what you have intended, I think that what you have intended and the result of this are two different things.
You see, you are defining '$a == 10' which is interpreted literally as a string value.
So you are trying to do something like:
if ('some string') ...
The result of this is true because a string that is not empty is a truthy value.
I think your intention however, was to test if the variable $a is equal to the integer value of 10?
In which case you actually need to do:
$final_str = $a == 10;
The result of this can be true or false depending on whether the variable $a is equal to 10 or not, that way your if condition will reflect the desired result?
EDIT:
If however you are trying to create some PHP code dynamically within your string you'd need to run it through eval and here is more information relating to the usage.
EDIT 2:
I would rather try to re-factor this into something more like:
$thisPage = 8;
$truthyPages = array(10,20);
if (in_array($thisPage,$truthyPages)) {
echo 'positive output';
} else {
echo 'negative output';
}
Or maybe even:
$a = 8;
// Step 1
$final_result = $final_result || $a == 10;
// Step 2
$final_result = $final_result || $a == 20;
if ($final_result) {
echo 'success';
} else {
echo 'failure';
}

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";

The strange ways of the "or" in PHP

PHP's or is an weird keyword. Here it is in a code snippet that makes me confused:
echo 0 or 1; // prints 1
$foo = (0 or 1);
echo $foo; // prints 1
$foo = 0 or 1;
echo $foo; // prints 0 for some reason
Why does the last one print 0 and not 1?
This is because of different operator precedence. In the third case, the assignment is handled first. It will be interpreted like this:
($foo = 0) or 1;
The || operator has a different precedence. If you use
$foo = 0 ||1;
It will work as you expect.
See the manual on logical operators
No, I wouldn't, that's because of operator precedence:
$foo = 0 or 1;
// is same as
($foo = 0) or 1;
// because or has lower precedence than =
$foo = 0 || 1;
// is same as
$foo = (0 || 1);
// because || has higher precedence than =
// where is this useful? here:
$result = mysql_query() or die(mysql_error());
// displays error on failed mysql_query.
// I don't like it, but it's okay for debugging whilst development.
It's ($foo = 0) or 1;. or has a lower operator precedence than = .
You should use || in this case, since it has a higher precedence than =, and thus will evaluate as you'd expect.
IIRC, the assignment operator (=) has higher precedence than or. Thus, the last line would be interpreted as:
($foo = 0) or 1;
Which is a statement that assigns 0 to $foo, but returns 1. The fist statement is interpreted as:
echo(0 or 1);
An as such will print 1.
Order of operations. The word "or" has much lower precedence than the corresponding "||". Lower, even, than the assignment operator. So the assignment happens first, and the value of the assignment is the first operand to the "or".
"or" is meant more to be used for flow control than for logical operations. It lets you say something like
$x = get_something() or die("Couldn't do it!");
if get_something is coded to return false or 0 on failure.
In the first two snippets, you are comparing 0 or 1 (essentially true or false). In the third snippet you are assigning 0, which works, and thus is true, so therefore the or condition is not executed.emphasized text
In your third example, the = operator has a higher precedence than or, and thus gets done first. The || operator, superficially the same, has a higher precedence than =. As you say, interesting.

In php, is 0 treated as empty?

Code will explain more:
$var = 0;
if (!empty($var)){
echo "Its not empty";
} else {
echo "Its empty";
}
The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??
http://php.net/empty
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)
Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x)
----------------+--------
$x = ""; | true
$x = null | true
var $x; | true
$x is undefined | true
$x = array(); | true
$x = false; | true
$x = true; | false
$x = 1; | false
$x = 42; | false
$x = 0; | true
$x = -1; | false
$x = "1"; | false
$x = "0"; | true
$x = "-1"; | false
$x = "php"; | false
$x = "true"; | false
$x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
In case of numeric values you should use is_numeric function:
$var = 0;
if (is_numeric($var))
{
echo "Its not empty";
}
else
{
echo "Its empty";
}
Use strlen() instead.
I ran onto the same issue using 1/0 as possible values for some variables.
I am using if (strlen($_POST['myValue']) == 0) to test if there is a character or not in my variable.
I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.
using empty() first and then strlen() is your best best if you need this as well, as:
if(!empty($var) && strlen($var)){
echo '"$var" is present and has a non-falsey value!';
}
From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.
empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()
To accept 0 as a value in variable use isset
Check if variable is empty
$var = 0;
if ($var == '') {
echo "empty";
} else {
echo "not empty";
}
//output is empty
Check if variable is set
$var = 0;
if (isset($var)) {
echo "not empty";
} else {
echo "empty";
}
//output is not empty
It 's working for me!
//
if(isset($_POST['post_var'])&&$_POST['post_var']!==''){
echo $_POST['post_var'];
}
//results:
1 if $_POST['post_var']='1'
0 if $_POST['post_var']='0'
skip if $_POST['post_var']=''
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but
without a value in a class)
From PHP Manual
In your case $var is 0, so empty($var) will return true, you are negating the result before testing it, so the else block will run giving "Its empty" as output.
From manual:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string) NULL
FALSE array() (an empty array) var
$var; (a variable declared, but
without a value in a class)
More: http://php.net/manual/en/function.empty.php
You need to use isset() to check whether value is set.
Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:
$myVar = '';
if (empty($myVar))
{
echo "Its empty";
}
echo "<br/>";
if ($myVar===0)
{
echo "also zero!";
}
just for notice $myVar==0 act like empty function.
if (empty($var) && $pieces[$var] != '0') {
//do something
}
In my case this code worked.
empty should mean empty .. whatever deceze says.
When I do
$var = '';
$var = '0';
I expect that var_dump(empty($var)); will return false.
if you are checking things in an array you always have to do isset($var) first.
use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.
Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.
BOOLEAN
If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).
So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.
BIT, TINYINT
If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.
proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.
0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.

Categories