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.