I have a quick question here. I know that the cakePHP find('first') function returns an array containing the first result if found, false otherwise. My question is this, what if I were to write a check like this:
if(result_is_array) // that means I have data
{
// do something
}
else // that means result is a boolean
{
// do something else
}
Instead of checking whether the result obtained from find('first') is an array or not, can I just say:
$result = $this->MyModel->find('first');
if($result)
{
// do something
}
In order words, if I get an array here, will that evaluate to TRUE in php? Is if(array()) equal to true in php?
YES, you can do
$result = $this->MyModel->find('first');
if($result)
An array with length > 0 returns true
Explanation is here in the docs
When converting to boolean, the following values are considered FALSE
an array with zero elements
Every other value is considered TRUE
A zero value array is false
An array with values in it is true
You can view this table to see what is evaluated as true vs false.
Instead of checking whether the result obtained from find('first') is
an array or not
Yes. Do it the second way:if ($result). If find returns an empty array or boolean false, the branch will not be executed.
The best part about doing it this way is that it makes it clear to the reader that you are checking for a non-empty value.
According to the documentation, if you try to treat an array as a boolean, the array will be considered true precisely when it's not empty.
Use the following if you are looking for a TRUE value:
if ( $result !== false )
{
// do something
}
An empty array will always evaluate to false or if it contain any key/values then it will evaluate to true. if $this->MyModel->find('first'); always returns an array then an empty result will evaluate to false and true other wise. so your code is perfectly valid.
Related
I can't understand why the last debugbar message is showing. Strangely enough $nest = 1, not true.
$nest = true;
$showcosts = false;
Debugbar::info($nest);
Debugbar::info($showcosts);
Debugbar::info("x" . $nest . "x");
Debugbar::info("x" . $showcosts . "x");
Debugbar::info($nest == true);
Debugbar::info($showcosts);
if ($showcosts && $nest) {
Debugbar::info("this should never show");
}
returns this:
true
false
x1x
xfalsex
true
false
this should never show
I'd like the last debugbar message not to show as only one of the conditions in the if statement is true.
I'm using Laravel 5.4 with PHP 7.
As mentioned in the comment above:
The string value of a boolean true is 1 which is why you get x1x when you concatenate strings. However the string value of a false should be the empty string and not the string false which means you should also see a xx outputed (not xfalsex) .
Make 100% sure that $showcosts is a boolean and not a string that contains the word false because that behaviour is consistent with checking a false string.
In addition as #NinoŠkopac pointed out, the simple if ($variable) check will be true for any value of $variable which is considered "truthy". This includes non-null objects, non-empty arrays, non-zero numbers and non-empty strings as well as the boolean true. In this case the string "false" is a non-empty string and is therefore a "truthy" value.
If you're getting values from a request query string or post (e.g. via $_POST or $_GET) you must keep in mind that all values are strings.
For this purpose PHP has a set of filtering functions that aim to help with this. There's filter_var and filter_input (and others, check the manual for more details).
You can use filter_var on any variable, for example in your case you could do:
$nest = filter_var($nest,FILTER_VALIDATE_BOOLEAN);
$showcosts = filter_var($showcosts ,FILTER_VALIDATE_BOOLEAN);
The FILTER_VALIDATE_BOOLEAN filter:
Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise.
You can also use filter_input to filter input directly.
For example if you have an input entry $_POST["nest"] then you can do:
filter_input(INPUT_POST,"nest",FILTER_VALIDATE_BOOLEAN);
This will also save you from an isset check.
in_array function is returning 1 if values exists, otherwise it returns an empty string. I am expecting it to return true or false.
Can someone please help me with this?
In PHP the integer value 1 is converted to true, check out the documentation on booleans in PHP here.
You could use it as a boolean like so
$arrBoolean = in_array("needle", $arr);
if ($arrBoolean) {
// Code
}
If you want it to say true or false you could do this
$arrBoolean = in_array("needle", $arr) ? 'True' : 'False';
echo($arrBoolean);
However, if you do that, then they are String representations of a boolean and do not actually work as a boolean, they will be just Strings.
I face a problem like this:
$area="Dhaka";
isset($area); //returns true which is OK
isset($area['division']); //returns true why?
// actually, any array key of area returns true
isset($area['ANY_KEY']);//this is my question 1
isset($area['division']['zilla');//now it returns false.
//as I know it should returns false but why previous one was true.
Now if I do this:
$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this
isset($area['division']['ANY_KEY']); // returns true why? question #2
Basically both of my questions are the same.
Can anyone explain this?
As with every programming language in existence, a string is stored as an array of characters.
If I did:
$area = "Dhaka";
echo $area[0];
It would return D.
I could also echo the whole string by doing:
echo $area[0].$area[1].$area[2].$area[3].$area[4];
PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.
So by doing:
echo $area['division'];
You would essentially be doing:
echo $area[0];
and again, getting D.
That's why isset($area['division']) returns a true value.
Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.
The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:
is_array($area) && isset($area['division'])
PHP lets you treat a string as an array:
$foo = 'bar';
echo $foo[1]; // outputs 'a'
So
$area['division']
will be parsed/executed as
$area[0];
(the keys cannot be strings, since it's not REALLY an array, so PHP type-converts your division string by its convert-to-int rules, and gives 0), and evaluate to the letter D in Dhaka, which is obviously set.
Okay, here's a solution rather than explaining why isset isn't going to work properly.
You want to check if an array element is set based on it's index string. Here's how I might do it:
function isset_by_strkey($KeyStr,$Ar)
{
if(array_key_exists($KeyStr,$Ar))
{
if(strlen($Ar[$KeyStr]) > 0 || is_numeric($Ar[$KeyStr] !== FALSE)
{
return TRUE;
}
return FALSE;
}
}
isset_by_strkey('ANY_KEY',$area); // will return false if ANY_KEY is not set in $area array and true if it is.
The best way to access a linear array in php is
// string treated as an linear array
$string= "roni" ;
echo $string{0} . $string{1} . $string{2} . $string{3};
// output = roni
It is expected behaviour.
PHP Documentation covers this
You can try empty() instead.
If it is returning true for keys that do not exist there's nothing you can do; however, you can make sure that it doesn't have a negative effect on your code. Just use array_key_exists() and then perform isset() on the array element.
Edit: In fact, using array_key_exists() you shouldn't even need isset if it is misbehaving just use something like strlen() or check the value type if array_key_exists returns true.
The point is, rather than just saying isset($Ar['something']) do:
if(array_key_exists('something',$Ar) )
and if necessary check the value length or type. If you need to check the array exists before that of course use isset() or is_array() on just the array itself.
I have very basic question regarding return value of a function, and checking the variable value.
function test($var1, $var2){
if ($var1 == $var2){
$var3 = "abc";
return $var3;
}
return false
}
$value = test($var1, $var2);
if ($value){
echo "Value is".$value; //should output abc.
} else {
echo "Not equal";
}
Is it ok to either return a value or return false? For example I am not returning TRUE, it is ok?
When i call the function, i store the return value in a variable $value. How can i check the function did return the $var3? Which of the if condition should be used?
if (!empty($value)) or if (isset($value)) or if ($value) or if (value != false)
Yes, it is common practice in PHP to return FALSE as an indicator of an error condition. (What constitutes an error is your own decision and depends on what the function is supposed to do.)
However, since PHP automatically casts values to Boolean that are of another type (like the empty string or 0, which evaluate to FALSE as well), you should do an explicit check for FALSE like this:
if ($value !== FALSE) ...
As Felix Kling notes in the comments, this is called "strict comparison" (or "identity comparison"). It checks if a value is identical to FALSE, where as != FALSE, == FALSE and if ($value) only check if a value could be interpreted as FALSE.
I'm not a PHP developer, but I don't think your first approach works.
There are other things than the boolean value false interpreted as false:
When converting to boolean, the following values are considered FALSE:
* the boolean FALSE itself
* the integer 0 (zero)
* the float 0.0 (zero)
* the empty string, and the string "0"
* an array with zero elements
* an object with zero member variables (PHP 4 only)
* the special type NULL (including unset variables)
* SimpleXML objects created from empty tags
http://php.net/manual/en/language.types.boolean.php
It's perfectly OK to return different data types.
If you want to check against false, use: if ($value !== false). If you get lost which condition to use, this will clarify it: http://www.php.net/manual/en/types.comparisons.php
Your function returns false, so I would go with that check: if ($value != false)
$var3 = "abc";
return $var3;
That's pointless. You're returning a value, not a variable. return "abc"; is perfectly fine.
Is it ok to either return a value or return false?
Yes, that's perfectly fine for a simple case such as this.
How can i check the function did return the $var3?
As said above, the function returns the value "abc", not $var3. You're saving it in a new variable $value. This variable is definitely set (you just created it right there), so there's no need for isset or empty. Just test whether its value is true or false (or whatever else you want to test for). So the way you're doing it in fine.
Yes, you can return pretty much anything from the function, or you can just "return" without returning anything. In your example, you'll get a string or "false" in return.
To check for false you either do if (!$variable) or if ($variable===false). Zero will return true if you do "if ($variable==false)" due to auto casting of zero to false (and any other positive number to true). Three "===" makes sure it really is false and nothing else. The isset($var) checks for existance, not value - and is not applicable to your example since your function will return a value or "false" and thus always exists.
The only right answer here is: it depends.
I always ask myself this question when creating a function like this. To answer it, I analyze what the function does, instead of what it returns.
For instance, if I have a getter, I expect to get a value, or nothing. In this case I often return null when nothing is found/something went wrong.
A test function like yours should return a boolean at all times, in my opinion. Returning a variable when you're checking for something to be true or false is semantically incorrect, I think.
Aside from the semantics: returning 0, false or null does not really matter when you're checking it with if (test($var1, $var2)), since it will all work the same. However, if you want some finer details, you want to do an identity check (===) rather than a equality check. In PHP this is sometimes the case, for instance strpos can return 0 or false, 0 being a match is found, and false is not. Therefore the following would fail:
// returns 0, which is casted to false, so the 'else' part is executed
if (strpos('a', 'abc')) {
// 'abc' contains 'a'
} else {
// 'abc' does not contain 'a'
}
So, long story short: it depends...
I am working on a signup form, I am using PHP and on my processing part I run some code, if a submitted item fails I then add it to an errors array.
Below is a snip of the code, I am at the point where I need to find the best method to determine if I should trigger an error.
So if there is a value set in the error array then I need to redirect and do some other stuff.
I was thinking of using isset or else is_array but I don't think that is the answer since I set the array using **$signup_errors = array()** wouldn't this make the is_array be true?
Can anyone suggest a good way to do this?
//at the beginning I set the error array
$signup_errors = array();
// I then add items to the error array as needed like this...
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
How does it work? When converting to boolean, an empty array converts to false. Every other array converts to true. From the PHP manual:
Converting to boolean
To explicitly convert a value to
boolean, use the (bool) or (boolean)
casts. However, in most cases the cast
is unncecessary, since a value will be
automatically converted if an
operator, function or control
structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the
following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
You could also use empty() as it has similar semantics.
Perhaps empty()?
From Docs:
Return Values
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)
Check if...
if(count($array) > 0) { ... }
...if it is, then at least one key-value pair is set.
Alternatively, check if the array is not empty():
if(!empty($array)) { ... }
Use array_filter if you already have keys, but want to check for non-boolean evaluated values.
<?php
$errors = ['foo' => '', 'bar' => null];
var_dump(array_filter($errors));
$errors = ['foo' => 'Oops', 'bar' => null];
var_dump(array_filter($errors));
Output:
array(0) {
}
array(1) {
["foo"]=>
string(4) "Oops"
}
Use:
<?php
if(array_filter($errors)) {
// Has errors
}
You could check on both the minimum and maximum values of the array, in this case you can have a large array filled with keys and empty values and you don't have to iterate through every key-value pair
if(!min($array) && !max($array)) { ... }
The language construct isset(), is for testing to see if variables and array elements are set and not NULL. Using is_array() would tell you if the argument you supply to it is an array. Thus, I do not think using isset() or is_array() would give you the correct and desired result that you are seeking.
The code:
$signup_errors = array();
means that ...
is_array($signup_errors);
would return true. However, this does not mean that the Boolean language rules of PHP would evaluate....
if($signup_errors)
{
//*Do something if $signup_errors evaluates to true*;
}
as true, unless some elements are added to it. When you did this,
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
you fulfilled the PHP language requirement for the array above to evaluate to true.
Now, if for some reason you wanted, or needed, to use isset() on the array elements in the future, you could. But, the conditional statement above is enough for you this case.
I should add an obvious answer here. If you initialise your error array as an empty array. And later want to check if it is no longer an empty array:
<?php
$errors = [];
if($errors !== [])
{
// We have errors.
}