Or operator not displaying content - php

Im trying to get something to be echoed if the user is on one of the two pages, but it isn't echoed
if(stripos($_SERVER['REQUEST_URI'], 'user.php') || ($_SERVER['REQUEST_URI'], 'message.php')) {
echo 'hello';
}

First of all, $_SERVER['REQUEST_URI'] will give you the URI which was given in order to access this page, not the actual page name. Use basename($_SERVER['PHP_SELF']) to get the actual page name.
And second, the condition of your if clause is also wrong. From the manual of stripos() function:
Returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So both of your conditions will fails if the needle matches exactly with the haystack. Instead check the condition like this:
if(stripos($haystack, $needle) !== false || stripos(stripos($haystack, $needle)) !== false) {
echo 'hello';
}
So the solution is like this:
if(stripos(basename($_SERVER['PHP_SELF']), 'user.php') !== false || stripos(basename($_SERVER['PHP_SELF']), 'message.php') !== false) {
echo 'hello';
}

if(stripos($_SERVER['REQUEST_URI'], 'user.php') || stripos($_SERVER['REQUEST_URI'], 'message.php')) {
echo 'hello';
}
Notice the stripos function in the clause after ||.

Wrap each conditional argument in its own block with parenthesis. Every function added to the condition must include 2 parenthesis.
IF ( ($a == $x) or ($b == $y) ) {}
if (
(stripos($_SERVER['REQUEST_URI'], 'user.php')) ||
(stripos($_SERVER['REQUEST_URI'], 'message.php'))
) {
echo 'hello';
}

Related

If statement is true OR not false [duplicate]

This question already has answers here:
Is there a difference between !== and != in PHP?
(7 answers)
difference between != and !== [duplicate]
(4 answers)
The 3 different equals
(5 answers)
Closed 3 years ago.
I have two statements like this:
$ready = true;
if($ready === true) {
echo "it's ready!";
}
And this:
$ready = true;
if($ready !== false) {
echo "it's ready!";
}
I know those mean the same thing as === true and !== false is the same thing. I see people use the negation type (is not false or is not {something}). like this: https://stackoverflow.com/a/4366748/4357238
But what are the pros and cons of using one or the other? Are there any performance benefits? Any coding benefits? I would think it is confusing to use the negation type rather than the straight forward === true. Any input would be appreciated! thank you
These do not mean the same thing, and you can see this demonstrated below:
$ready = undefined;
if($ready === true) {
console.log("it's ready 1");
}
if($ready !== false) {
console.log("it's ready 2");
}
When in doubt, stick with ===. You're comparing to exactly what it should be. "This should exactly be equal to true" vs "This should be equal to anything but exactly false" are 2 separate statements, the second including a lot of values that would be true (As demonstrated above, undefined is not exactly false, so this would be true).
Most PHP functions return false as failure, such as strpos, from the manual it says:
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
So it returns an integer or false, then it is wrong to use strpos() === true
strpos() !== false is the right way to check the result.
It is not about performance and they are not the same. It helps us in reducing unnecessary if else statements.
Consider this: there is a variable foobarbaz whose value can be anything among foo/ bar/ baz/ foobar/ barbaz. You need to execute a statement if the value is not foo. So instead of writing like this:
if(foobarbaz === "bar" || foobarbaz === "baz" || foobarbaz === "foobar" || foobarbaz === "barbaz") {
//some statement
}
else if(foobarbaz === "foo") {
//do nothing
}
You can write something like this:
if(foobarbaz !== "foo") {
//some statement
}
You can see we were able to eliminate the unnecessary else statement.
In php == compare only the values are equal. For and example
$ready = 'true';
if($ready == true) {
echo "true";
}
else{
echo "false";
}
It print true.But if it is compare with === it not only check the values but also it check the datatype. So it compares with === it print the false.
Talking about !== it's work as the same. So it's not a problem to output if you use
if($ready === true)
or
if($ready !== false)
Can't compare these two because both are same.

Confused with use of strpos and !==

Confused!
I am trying to extract our localsites' names which are embedded in our WordPress website's structure, ie https://www.website.co.uk/site99/folderX/page. In the URL the localsite name is all lower case without any gaps, whereas the 'display name' of the localsite has a Starting capital and a gap between words. What am I doing wrong here?
if(strpos($_SERVER['REQUEST_URI'], '/site01/') !== false) { $categoryIdOrSlug = 'Site 01';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site02/') !== false) { $categoryIdOrSlug = 'Site 02';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site03/') !== false) { $categoryIdOrSlug = 'Site 03';}
endif;
so what I am looking for is where /site99/ is in position 0 of the slug.
If you are in https://www.website.co.uk/site99/folderX/page
Then : $_SERVER['REQUEST_URI'] will be /site99/folderX/page
if (strpos($_SERVER['REQUEST_URI'], '/site98/') !== false) { $categoryIdOrSlug = 'Site 98';} // strpos($_SERVER['REQUEST_URI'], '/site98/') will be false
elseif (strpos($_SERVER['REQUEST_URI'], '/site99/') !== false) { $categoryIdOrSlug = 'Site 99';} // strpos($_SERVER['REQUEST_URI'], '/site98/') will be 0 (which is success run & is true)
See different outputs:
echo strpos($_SERVER['REQUEST_URI'], '/site99/'); // OUTPUT: 0
Here, strpos() return the index/position at which the 2nd param(/site99/) is present in first param($_SERVER['REQUEST_URI']).
The strpos() function finds the position of the first occurrence of a string inside another string. Related functions: strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive)
var_dump(strpos($_SERVER['REQUEST_URI'], '/site98/'));
Output will be bool(false). Why its false because the string was not found in param one. If its found, then the out will be a int of position like int(25).
var_dump(strpos($_SERVER['REQUEST_URI'], '/site99/'));
Output will be int(0) because strpos() has successfully found /site99/ in $_SERVER['REQUEST_URI'].
And, normally === or !== are used for Boolean value(TRUE/FALSE) comparisons.
No need to get confused with strpos() and !== both are entirely different, one returns a position index value(if found) or FALSE, if not found required string. Whereas, !== compares left & right side values of operator & says TRUE or FALSE.
Reply to your comment:
Yes, you are getting correct answer. As you said to making ensure we are using if() check.
You see we are getting int(0) while var_dump(strpos($_SERVER['REQUEST_URI'], '/site99/'));. If we have a index value(even its 0) its treated as a success run(true). That is, the string you are searching is found in index 0 or at a particular position of $_SERVER['REQUEST_URI']. if() makes sure that the check is correct, int(0) !== false means int(0) is a success run(which is also said as true). So if(int(0) !== false) can be said also as if(true !== false) which is true & so $categoryIdOrSlug = 'Site 99'; will run.
if() can also be written as:
if (strpos($_SERVER['REQUEST_URI'], '/site98/')) { $categoryIdOrSlug = 'Site 98';}
elseif (strpos($_SERVER['REQUEST_URI'], '/site99/')) { $categoryIdOrSlug = 'Site 99';}
echo $categoryIdOrSlug; // output: Site 99
You cant check by === 0 because we cant say the position at which strpos() founds the searching string, it may vary.

Filter specific column in array in php

I am trying to filter a specific column in an array in php using the code below:
(strpos( 'meeting',$event['categories'] ) == false )
It is not working actually. An example of what [categories] hold is:
$event['categories'] = 'meeting;skype'
Thanks in advance!
You need to flip the arguments to strpos():
if (strpos($event['categories'], 'meeting') === false) {
echo $event['categories'] . ' does not contain "meeting"';
}
Also, use strict comparison (=== vs ==), as meeting could be at the start of the string, and then strpos() would return 0, which would evaluate to false (which would be wrong in that case).
For reference, see:
http://php.net/manual/en/function.strpos.php
For an example, see:
https://3v4l.org/Ab4ud
I think you should use === not == and also flip the arguments
(strpos($event['categories'] , 'meeting') === false )
strpos could return 0 or false and when you use == then zero is like false
see compression operators
see strpos() docs
<?php
$event = ['categories' => 'meeting;skype'];
$needle = 'meeting';
$haystack = $event['categories'];
if( ($pos = strpos( $haystack, $needle )) === false){
echo "\n$needle not found in $haystack";
}
else
{
echo "\n$needle exists at position $pos in $haystack";
}
See demo
The two things to watch out for are the order of the parameters for strpos() as well as doing a strict comparison using the identity operator ("===") so that when the 'needle' appears at position zero of the 'haystack' it's not mistakenly deemed a false result which occurs if you use the equality operator ("=="), given that in PHP zero == false.

strpos not finding one word in a string

In the following code, if I set $what to 'red', it doesn't find it, whereas it finds green and blue. Why and how to make it find red as well?
$where = 'red,green,blue';
$what = 'blue';
if (strpos($where, $what) == true) {
echo 'found';
}
strpos returns the index of the found string. In this case the index is 0 and your check for == true will fail. Try:
strpos($where, $what) !== false
The documentation provides more information.
strpos will return false if your string isn't there. Otherwise, it returns the position of your string.
In this case, 'red' is at the start of the string, which means that it's at position 0; and 0 evaluates to false.
You need to do a boolean compare on the result:
if(strpos($word, 'red') === false)

verify, if the string starts with given substring

I have a string in $str variable.
How can I verify if it starts with some word?
Example:
$str = "http://somesite.com/somefolder/somefile.php";
When I wrote the following script returns yes
if(strpos($str, "http://") == '0') echo "yes";
BUT it returns yes even when I wrote
if(strpos($str, "other word here") == '0') echo "yes";
I think strpos returns zero if it can't find substring too (or a value that evaluates to zero).
So, what can I do if I want to verify if word is in the start of string? Maybe I must use === in this case?
You need to do:
if (strpos($str, "http://") === 0) echo "yes"
The === operator is a strict comparison that doesn't coerce types. If you use == then false, an empty string, null, 0, an empty array and a few other things will be equivalent.
See Type Juggling.
You should check with the identity operator (===), see the documentation.
Your test becomes:
if (strpos($str, 'http://') === 0) echo 'yes';
As #Samuel Gfeller pointed out: As of PHP8 you can use the str_starts_with() method. You can use it like this:
if (str_starts_with($str, 'http://')) echo 'yes';
PHP does have 2 functions to verify if a string starts with a given substring:
strncmp (case sensitive);
strncasecmp (case insensitive);
So if you want to test only http (and not https), you can use:
if (strncasecmp($str,'http://',7) == 0) echo "we have a winner"
check with
if(strpos($str, "http://") === 0) echo "yes";
as == will turn positive for both false & 0 check the documentation
Another option is:
if (preg_match("|^(https?:)?\/\/|i", $str)) {
echo "the url starts with http or https upper or lower case or just //.";
}
As shown here: http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/
strncmp($str, $word, strlen($word))===0
Is a bit more performant than strpos
Starting with PHP 8 (2020-11-24), you can use str_starts_with:
if (str_starts_with($str, 'http://')) {
echo 'yes';
}
PHP 8 has now a dedicated function str_starts_with for this.
if (str_starts_with($str, 'http://')) {
echo 'yes';
}
if(substr($str, 0, 7)=="http://") {
echo("Statrs with http://");
}
There's a big red warning in the documentation about this:
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.
strpos may return 0 or false. 0 is equal to false (0 == false). It is not identical to false however, which you can test with 0 === false. So the correct test is if (strpos(...) === 0).
Be sure to read up on the difference, it's important: http://php.net/manual/en/language.operators.comparison.php

Categories