in_array not working properly in Laravel 5 - php

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.

Related

Is an array considered as boolean true in php?

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.

What is the PHP best practice for using functions that return true or false?

After playing with PHP, I discovered that true is returned as 1 and false as null.
echo (5 == 5) // displays 1
echo (5 == 4) // displays nothing
When writing functions that return true or false, what are the best practices for using them?
For example,
function IsValidInput($input) {
if ($input...) {
return true;
}
else {
return false;
}
}
Is this the best way to use the function?
if (IsValidInput($input)) {
...
}
How would you write the opposite function?
IsBadInput($input) {
return ! IsValidInput($input);
}
When would you use the === operator?
After playing with PHP, I discovered that true is returned as 1 and false as null.
That is not true (no pun intended). PHP, like many other languages, has "truthy" and "falsy" values, which can behave like TRUE or FALSE when compared to other values.
It is so beause PHP uses weak typing (vs. strong typing). It automatically converts different types of values when comparing them, so it can eventually compare two values of the same type. When you echo TRUE; in PHP, echo will always output a string. But you passed it a boolean value, that has to be converted to a string before echo can do its job. So TRUE is automatically converted to the string "1", while FALSE is converted to "".
When would you use the === operator?
This weak, or loose, typing is the reason PHP uses two equality operators, == and ===. You use === when you want to make sure both values you are comparing are not just "equal" (or equivalent), but also of the same type. In practice:
echo 1 == TRUE; // echoes "1", because the number 1 is a truthy value
echo 1 === TRUE; // echoes "", because 1 and TRUE are not the same type (integer and boolean)
When writing functions that return true or false, what are the best practices for using them?
Be precise when you can, returning the actual boolean TRUE or FALSE. Typical cases are functions prefixed by is, like isValidInput. One usually expects such functions to return either TRUE or FALSE.
On the other hand, it's useful to have your function return a "falsy" or "truthy" values in some cases. Take strpos, for example. If it finds the substring in position zero, it returns 0 (int), but if the string is not found, it returns FALSE (bool). So:
$text = "The book is on the table";
echo (strpos($text, "The") == FALSE) ? "Not found" : "Found"; // echoes "Not found"
echo (strpos($text, "The") === FALSE) ? "Not found" : "Found"; // echoes "Found"
function isValidInput($input){
return ($input ...); // if your test returns true/false, just return that result
}
Your last example is missing an argument, otherwise fine:
function isBadInput($input){
return !isValidInput($input);
}
Sure. Unless you need it in a different sort of structure, e.g. a while loop.
You never would. Always invert the normal function directly.
When you need to differentiate false from 0, '', etc.
After playing with PHP, I discovered that true is returned as 1 and false as null.
No.. true and false are returned as boolean true and false. When you echo output it must be cast to a string for display. As per the manual:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string value.
As for the rest: that's fine, yes, yes, when you want exact type matches, to avoid type juggling in comparisons, e.g. "1" == true is true but "1" === true is false.
function isValidInput($input) {
return ($input...);
}
if(isValidInput($input))
...
if(!isValidInput($input)) // never rewrite inverse functions
...
if(isValidInput($input) === false) {
// Only run if the function returned a boolean value `false`
// Does the same thing as above, but with strict typing.
}

Is it correct way to return value in PHP

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...

Boolean issues in PHP

I have a question regarding bools in php. I have a stored mysql proc that is returning a boolean. When this value is grabbed on the php side it displays the value as being a 0 or 1. This all seems fine to me and I have read in the php manual that php will interpret a 0 or 1 as false or true at compile time but this does not seem to be the case to me. I have gone a step further and casted my returned value with (bool) but this still does not seem to work.
My if statements are not properly firing because of this. Does anyone know what is going on? Thanks for the help.
MySQL does not have a proper BOOL or BOOLEAN data types. They are declared as synonyms for TINYINT(1). Your procedure will return 0 or 1, which being on non-PHP ground will get transformed into a string in PHP land, so in PHP you have the strings '0' and '1'.
It is weird however that boolean casting does not convert them to the appropriate booleans. You may have some other bugs in your code.
Are you trying to cast the direct result from the query? Because that one is probably an array and:
var_dump((bool) array('0')); // true
Maybe this is your problem. Inspect the returned result.
It sounds like the boolean value is being returned as a string.
Try something like this:
$your_bool = $field_value === "0" ? false : true;
Using the script below. (You'll have to add HTML line break tags before the word "Boolean" inside the left quote to make the output look like my sample; when I do, Firefox interprets them, making the format look strange).
You'll see that the second line produces a null value which MySQL sees as something different from 0 or 1; for TINYINT it stores the PHP true value correctly but nothing for the PHP false, since a null value has no meaning for TINYINT.
Line four shows type casting with (int) is a way to insure that both PHP true and false are stored to MySQL TINYINT Boolean fields. Retrieving the resultant integers from MySQL into PHP variables works since integers are implicitly cast when assigned to PHP Boolean variables.
echo "Boolean true=".true;
echo "Boolean false=".false;
echo "Boolean (int)true=".(int)true;
echo "Boolean (int)false=".(int)false;
Here's the output from PHP 5.3.1 for MySQL 5.1.41:
Boolean true=1
Boolean false=
Boolean (int)true=1
Boolean (int)false=0
Oh! And PHP Boolean literals may be all lowercase or uppercase with the same result... try it yourself.
I use a helpful function "to_bool" for anything I'm not sure of the type of:
function to_bool($value, $default = false)
{
if (is_bool($value)) {
return $value;
}
if (!is_scalar($value)) {
return $default;
}
$value = strtolower($value);
if (strpos(";1;t;y;yes;on;enabled;true;", ";$value;") !== false) {
return true;
}
if (strpos(";0;f;n;no;off;disabled;false;null;;", ";$value;") !== false) {
return false;
}
return $default;
}
Then:
if (to_bool($row['result'])) { ... }

Is there a way to get "true"/"false" string values from a Boolean in PHP?

When I cast to Boolean (using (bool)), is there a built in way to get PHP to actually return the constants true or false. At the moment I'm getting 1 or blank, which evaluate to true and false respectively.
I want the value returned for clearer semantics. However, if I can't get it, I'll just settle with 1 and blank.
In case you're too lazy to do a comparison and echo a string or if you just want to keep it short you can use :
var_export($boolean, true); // the second parameter is to return and not output
PHP: var_export
PHP displays boolean values as 1 (true) or empty string (false) when outputted.
If you want to check if it's true or false use == (if implicit conversion is OK) or === (if it's not). For example:
echo $val ? 'true' : 'false'; // implicit conversion
echo $val === true ? 'true' : 'false'; // no conversion
I don't know of any way to make PHP output boolean values natively as true or false.
If you're looking for the strings "true" and "false," a ternary conditional would be perfect:
<?=(($boolean) ? "true" : "false")?>

Categories