This is something I don't understand. If I assign the variable $bool the value true, and then later in the code change it to false, the variable $bool looses its value?
FYI: This reassignment of values is happening in a function in the class.
class csvcheck {
function booleonChange () {
echo "<br>";
$bool = true;
echo "1. assignment of booleon: " . $bool ."<br>";
$bool = false;
echo "2. assignment of booleon: " .$bool . "<br>"; // value of $bool is lost. Why??
}
}
$csv = new csvcheck;
$csv->booleonChange();
If this code is executed in the browser, you will see this:
assignment of booleon: 1
assignment of booleon:
If i remember correctly, the PHP boolean false is actually converted to an empty string rather than the value of 0 that I believe you are looking for.
Actually just looked for it, and this seems to confirm:
PHP printed boolean value is empty, why?
Related
I already know what is_int() is used for. But I only know that to print the result of this function we need to use the var_dump() function. So can someone explain to me why echo, print or print_r() cannot display is_int()?
$var1 = '123';
var_dump(is_int($var1)); // return False;
$var2 = '123';
echo/print/print_r($var2); // Not working
In PHP (boolean) false will be converted to "" (empty string) and boolean (true) will be converted to 1 so when you print_r and the return value is false then you will get the empty string. So either use the var_dump to get the variable details where it will give you the type and value both.
Here is the way to echo the true and false based on the result. you can use this too
$var1 = '123';
echo is_int($var1)?'true':'false';
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.
I'm trying to simplify some code. I've found that if you assign a value within an if statement, but the value ends up being null, then the evaluated if is FALSE.
Example:
if($myvar = doSomething()) {
echo '$myvar = '.$myvar;
}
else {
echo "was null";
}
function doSomething() {
$a = null;
return $a;
}
The script above will display "was null". However, if $a = 1, then it will display "myvar = 1".
I've tried to find some documentation around this behaviour but haven't been successful. All of my sources are close, but don't describe it well.
My question: Is this expected behaviour? If doSomething() returns null, is what I'm doing equivalent to if(null) {...?
EDIT: YES I mean '=' not '==' in the if statement. What I'm asking is it expected that this should always return false: if($a = null) whereas this returns true if($a = 1)
What you're doing is fully expected. The value of the assignment expression $a=b is the assigned value b. So,
if($myvar = doSomething()) { ...
is equivalent to
$myvar = doSomething();
if ($myvar) { ...
This behavior is completely unrelated to the if statement. The documentation clearly states, in the second paragraph:
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.
Try to call function in variable.
$getvar = doSomething();
if($myvar == $getvar) {
// stuff
}
I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}
I'm attempting to troubleshoot a problem, and need to understand what this if statement is saying:
if ($confirmation = $payment_modules->confirmation()) {
All the resources I can find only show if statements with double equal signs, not single. Is this one of the shorthand forms of a php if? What is it doing?
(If it's actually wrong syntax, changing it to a double equal sign doesn't resolve the problem. As-is, in some scenarios it does return true. In the scenario I'm troubleshooting, it doesn't return true until after I refresh the browser.)
Any help is greatly appreciated!!!
It's a form of shorthand, which is exactly equivalent to this:
$confirmation = $payment_modules->confirmation();
if ($confirmation) {
}
This will first assign the value of $payment_modules->confirmation() to $confirmation. The = operator will evaluate to the new value of $confirmation.
This has the same effect as writing:
$confirmation = $payment_modules->confirmation();
if ($confirmation) {
// this will get executed if $confirmation is not false, null, or zero
}
The code works because an assignment returns the value assigned, so if $payment_modules->confirmation() is true, $confirmation will be set to true, and then the assignment will return true. Same thing for false.
That's why you can use a command to assign to many variables, as in a = b = 0. Assigns zero to b and returns that zero. Therefore, it becomes a = 0. And a receives zero and it will return that zero, which can or can not be used.
Sometimes people like to do an assignment and then check if the assignment went through okay. Pair this up with functions that return false (or equivalent) on failure, and you can do an assignment and a check at the same time.
In order to understand this, remember that assignments are a kind of expression, and so (like all expressions) have a return value. That return value is equal to whatever got put into the variable. That is why you can do something like
a = b = c = 0;
to assign all of those variables at the same time.
= means assignment ( $a = 1 ), == is for comparison ( true == false is false ). I think in your example it should use = because it assigns it to the return value of confirmation, which should be something that evaluates to true.
Try doing a var_dump:
var_dump( $payment_modules->confirmation() );
See what boolean it evaluates to, and from there you can troubleshoot. Post more code if you want more help.
class test() {
public function confirmation() { return true; }
}
$boolean = test::confirmation();
var_dump( $boolean );
Will equate to true