strpos issue with 0==false? - php

I'm using strpos to find the position of a string in another string. I first check if the string is found at all in there. Here's my line:
if (strpos($grafik['data'],$ss1)<>false && strpos($grafik['data'],$ss2)<>false && strpos($grafik['data'],$ss1) < strpos($grafik['data'],$ss2))
I check if both strings are contained and then I want the first one to be placed before the second one. In the php manual it says that strpos returns false when string is not found. However if my string starts at the zero position (strpos returns 0 since its the beginning), it seems like this statement
strpos($grafik['data'],$ss1)<>false
is false. Somehow 0==false ? How do I make the statement true when strpos returns 0 ?

From http://www.php.net/manual/en/function.strpos.php:
Warning
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
You have to use the === operator instead of ==.
In your case, instead of using <>, use !==:
strpos($grafik['data'], $ss1) !== false
This will return TRUE if $ss1 is found in $grafik['data']

You need to check with ===. This will make sure you have exact false and not 0.

This function behaves unpredictably, so to be sure it'll have deterministic behavior use either
if(strpos($text,$string)===false)
or test it using a variable
$pos=strpos($text,$string);
if($pos===false)

Related

php strstr/strpost not working

I'm working on a quite simple if-else statement, which containes the strstr or strpos condition.
The code is :
if(strpos(strtolower($ofcountry),"except")){
....
}
Can you tell me what is wrong with this code?
Greetings Phil
strpos returns False when the string is not found, and 0 when the string is found in position 0. But in an if clause, 0 is also false! How can you tell one from the other? Easy: === (or !==) operator will return false only against absolute False. Not against 0. So use it like this:
if(strpos(strtolower($ofcountry),"except") !== False){
http://php.net/manual/en/function.strpos.php , check first pink Warning

PHP's preg_match() acts weirdly

I found this, when I'm working in regex validation in PHP.
I've used preg_match function to validate a string.
I've just printed that value returned by preg_match to ensure working flow.
During that I've found a thing. But can't understand their concept.
That was preg_match() returns 1 if the match found. Otherwise, it will return 0. But sometimes my print function didn't print anything.
After I went through the PHP manual to know all of its return value...
There they posted as follows...
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
And then I used var_dump to know anything is printed or not...
This helped me to know that's a Boolean false.
But I'm curious to know why it returns boolean false, when I'm just putting " ! " (not) before the preg_match()?
Following is my code,
echo preg_match("/script/", "script") // ===> this returns 1
echo !preg_match("/script/", "script") // ===> this returns Boolean false
I think it has to return integer 0 (zero)... What is its functionality? Or did I do anything wrong in syntax?
I've tried this in the OpenCart 2.0.0.0 system administrator controller module.
The ! operator will always return a Boolean value.
For a unary ! operator the type of the result is bool. The value of the operand is converted to type bool and if it is TRUE then the of the operator result is FALSE, and the result is TRUE otherwise.
Language specification reference: Expressions
The normal conversion rules to a bool are applied to the value.
You're not echoing preg_match's return value when you put a ! in front of the function. You're using PHP's operator to determine if it loosely evaluates to true or false.
!preg_match("/script/","script") is the same as preg_match("/script/","script") == false. Note the == and not the ===. 0, null, empty string, and Boolean false will evaluate loosely to false.

String compare on a bool

I'm pretty sure this is a simple fundamental flaw in my newb PHP knowledge, but I was surprised when the following happened:
$result is TRUE... so why is it considered equal to the string "email"? I'm guessing this is because, technically, it's a bool and it isn't false? So when it's compared against a string (e.g. "email") it returns true.
Should I change my method to return as the result as a string containing "true" (instead of return true; on success), or is there another way I should be doing this?
Thanks.
Yes, true is equal (==) to a non-empty string. Not identical (===) though.
I suggest you peruse the type comparison table.
It returns true because php will try to convert something to be able to compare them. In this case it probably tries to convert the string on the right side to a bool which will be true in this case. And true == true is ofcourse true.
By doing $result === "email" (triple =) you tell PHP that it shoudn't do conversions and should return false if the types don't match.
if($result === "email") will do the trick but personally I would never go this way.

Find text in string in PHP

This should be pretty straightforward, but I can't seem to find an explanation anywhere on how to do it.
I have a string in PHP. That string might contain within it somewhere the substring ":ERROR:". I need to find if it has that string. strpos() has worked perfectly up to this point, until today when ":ERROR:" was the first item in the string, so strpos() returned 0, so the program kept running thinking it had no error.
I don't need to replace the string, or do any manipulation to it, I just need a simple true/false answer to "does :ERROR: exist in the string?"
strpos returns false when the string is not found, so check for false instead of making an implicit condition.
if(strpos($string, ':ERROR:') !== false) {
// Do something...
}
As Anurag said in the comments, with functions like these it's always best to do a strict comparison (=== instead of just leaving out the operator or using ==) because that's a common source of bugs, especially in PHP, where many functions can return values of different types.
The PHP Manual on strpos():
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
if (strpos($myString, ":ERROR:") !== FALSE) {
// Error!
}
You can also avoid the strpos() problems of not checking with a strict type operator by using the lesser known strstr()
if(strpos($string, ':ERROR:') !== false){
//found ':ERROR:' in string
}
"[strpos()] [r]eturns the position as an integer. If needle is not found, strpos() will return boolean FALSE."
http://php.net/manual/en/function.strpos.php
If the position is 0, then merely using == or != will evaluate 0 and false as equivalent. So use === or !== to avoid type coercion.

What precautions should I take when using '0' in PHP as a number?

In PHP 0 is treated as boolean false. Hence, whenever I'm in a situation where a function has to return a numerical value and I have it return 0, or when I have a MySQL bool column with possible values of 0/1, and I use code such as this:
$active=(isActive()) ? 1 : 0;
$this->db->set('isActive',$active);
I get a feeling in the back of my mind that the 0 might be converted to null or an empty string e.g "".
What precautions do I need to take in order to have 0 always treated as an integar and not anything else?
If you want PHP to evaluate a statement with 'false' being the only 'false', use === instead of the usual ==
PHP does allow you to cast variables to a certain type.
<?php
$value = (bool) 0;
$value3 = (int) 3;
?>
If you always want 0 to be treated as a int, cast it as one.
There are a few places where 0 and '0' are treated a little bit specially. This is almost always because of automatic type co-ercion. You've already noticed where 0 evaluates to false. So if PHP has a reason to convert '0' to an integer, then that will also evaluate to false. The prime one to watch out for is the empty() function. This is documented, BTW.
I rarely use empty() because of this very problem, in fact. It makes much more sense to check more narrowly, hence I use isset(), is_null() and === false or even == 0 (or != 0). There are other checks, too. I have DB handler code that not only checks using is_null() but also does is_numeric().
Other places to watch out for are where you use other developer's code who aren't completely careful with how 0 works in automatic type co-ercion. If you give a function a 0 but it ends up using a null when it should be using a 0 then you've probably found a bug in the API and should raise it with the developer. In fact, they're probably using empty() when they should be using isset() and/or is_null(). :-)
None. 0 is 0, even if logical evaluations consider it a false value, that doesn't change its actual value.
I can't find of a single case where PHP would convert 0 to null or "". If it has to convert it to a string, it will be "0", to a boolean it will be false. There's no "null" type, so really your 0 is safe with PHP. false is converted to "" (an empty string) when cast as a string, but integers are safe.
Now it's not a guarantee that third-party code won't behave strangely when passed an integer when they expected something else, but you're mostly safe.
If you set a variable to 0, the variable remains as 0 unless you cast it to something else. The type is still integer.
You can check whether a variable is by using the is_numeric() function.
Example:
$active=(isActive()) ? 1 : 0;
if(is_numeric($active)){
$this->db->set('isActive',$active);
}
Or You can use the comparison operator === instead of the usual ==. it'll compare the data type as well as the content of the variable.
$active=(isActive()) ? 1 : 0;
if($active === 0 || $active === 1){
$this->db->set('isActive',$active);
}
Hope this helps!
Using the === comparison operator is best as it checks that the types are equal as well as their values. In php if you do:
Your best bet is to use true and false where you can, rather than setting 1 and 0 for flags. In your example, do:
$active=(isActive()) ? true : false;
or even better (assuming isActive returns a proper boolean):
$this->db->set('isActive',isActive());
rather than:
$active=(isActive()) ? 1 : 0;

Categories