I have the following JS:
if(window.location.href.indexOf("search.php") != -1
|| window.location.href.indexOf("list.php") != -1
|| window.location.href.indexOf("view.php") != -1
|| window.location.href.indexOf("contact.php") != -1) {
But want to convert it to PHP. What is the equivalent of indexOf in PHP or the best way to do this in PHP.
I don't understand the strpos examples people are linking to below. Perhaps an example more in line with what I have done in JS?
The question asks for an equivalent. PHP's strpos() does not work on an array, whereas javascript's indexOf does (by treating a string as an array automatically). So here's a PHP equivalent
function indexOf($array, $word) {
foreach($array as $key => $value) if($value === $word) return $key;
return -1;
}
// Example: indexOf(['hi','bye'], 'bye') returns 1
Although your JavaScript code is using indexOf(), PHP actually has a better way of handling what you want to achieve.
You simply have to check the script name in your URL, then perform an action(s) based on it.
In my opinion, PHP switch statement is better than if statements in combination with PHP strpos() function.
Below is an illustration of how you can achieve that using a PHP switch statement:
switch(basename($_SERVER['SCRIPT_NAME'])) {
case 'search.php':
// Script to run for search.php
break;
case 'list.php':
// Script to run for list.php
break;
case 'view.php':
// Script to run for view.php
break;
case 'contact.php':
break;
default:
// Perform code on anything except the above cases.
break;
}
strpos() should do the trick, also it returns boolean false on failure.
JS version:
The indexOf() method returns the position of the first occurrence of a
specified value in a string. This method returns -1 if the value to
search for never occurs. Note: The indexOf() method is case sensitive.
PHP version:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Find the numeric position of the first occurrence of needle in the
haystack string. 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.
In reply to your secondary question, strpos could be used as follows:
if (strpos($_SERVER['SCRIPT_NAME'], "search.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "list.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "view.php") !== false
|| strpos($_SERVER['SCRIPT_NAME'], "contact.php") !== false) {
...though indeed Rawkode's answer is more elegant.
strpos();
You should use mb_strpos() if you're not using ISO-8859-1 encoding (UTF-8 or others).
Related
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.
Good day,
I have the following string :
[Star]ALERT[Star]Domoos detects blabla[blabli]
For strange reasons, the code below does not detect the star at the very first character. I read in the php documentation that the first character has an index of 0. However, if I am looking for the '[', the function works very well.
What I am trying to achieve is to ensure that the first character of my string is really a * (star). Strangely, if I enter $pos1 = strpos($inputString, '*', 1), the star shown at position '6' would be returned.
I don't quite understand why my code does not work as expected (i.e. does not enter into the 'true' condition)
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
if ($pos1 == True)
{
echo 'position' . $pos1;
}
Do you have any suggestion that would help me to overcome this issue?
Thanks a lot for your appreciated support.
change condition to
if ($pos1 != False)
{
echo 'position' . $pos1;
}
as strpos will return position at (integer) or False
If you look at the manual:
Find the numeric position of the first occurrence of needle in the
haystack string.
In your test case, the numeric position is 0 and 0 != true.
Also see the warning in the manual:
Warning This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
So the condition you really want is:
if ($pos1 !== false)
You don't need strpos. As string is an array of characters so you can do like this
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$compare_char= $inputString[0];
if($compare_char=="*"){
//do something.
}
As i suppose it is fast too rather than on searching through strpos
Actually issue is that when you are looking at 0 position the value which you get is 0 and when you are checking that in if condition with True, it will always fail because 0 will be evaluated as False. To resolve this you can use
if($pos1 !== False)
The function strpos returns false if there is no existence of what you search. So make a check like the following:
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*', 0);
return $pos1 !== false ? 'position ' . $pos1 : '..';
$pos1 returns 0 and this is treat as False so we cant take it as True so we can use here isset function.
$inputString = '*ALERT*Domoos detects blabla[blabli]';
$pos1 = strpos($inputString, '*',0);
if (isset($pos1))
{
echo 'position' . $pos1;
}
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)
if (strrpos($_POST['security_data'], $OrderReference) === false ||
md5($_POST['security_data'] . $sekey) != $_POST['security_hash'])
{
return;
}
I don't understand why is strrpos in there and === "3 equals"
and what is the dot "." doing in $_POST['security_data'] . $sekey
Thank You
strrpos returns the position of the substring.
echo strrpos("Hello", "e"); // outputs `1`
. is concatenation.
echo "Hello "."There"; // outputs: 'Hello There'
=== checks type as well as equality.
var_dump(1 == true); // true
var_dump(1 === true); // false
Here's a translation to C#:
string hash = MD5.Create().ComputeHash(Request.Form["security_data"] + sekey);
if (!Request.Form["security_data"].Contains(OrderReference)
|| hash != Request.Form["security_hash"])
{
return;
}
strrpos returns false if the string isn't found (don't know which string in which, but the docs will tell you)
=== compares type as well instead of just value. This is done so php doesn't to any casting, for example 0 == false (0 represents false in php as well) but 0 !== false as 0 isn't the same type as false.
the . is the concat operator in php.
strrpos is "return position of substring within a string, starting from the right (end) side". === is the PHP strict comparison, which compares type AND value. The strpos functions CAN return a legitimate 0 as a position, which is the very start of the string. But 0 evalutes to boolean FALSE in PHP, so the === check ensures that you're looing at a real false (strrpos found nothing) and not just "strrpos found string at position zero".
The dot (.) connects between 2 strings, and the 3 equals checks if the returned value is in the same type as what it compared to
If the contents of the variable $OrderReference are not found in the POST variable security_data, or the MD5 hash of the POST variable security_data, concatenated with (that's the . operator in PHP) the variable $sekey isn't equal to security_hash, return from the function.
=== is used to ensure that the return from strrpos() is the boolean FALSE rather than the possible valid return value of 0. === is for strict type comparison.
I've seen a lot of php code that does the following to check whether a string is valid by doing:
$str is a string variable.
if (!isset($str) || $str !== '') {
// do something
}
I prefer to just do
if (strlen($str) > 0) {
// something
}
Is there any thing that can go wrong with the second method? Are there any casting issues I should be aware of?
Since PHP will treat a string containing a zero ('0') as empty, it makes the empty() function an unsuitable solution.
Instead, test that the variable is explicitly not equal to an empty string:
$stringvar !== ''
As the OP and Gras Double and others have shown, the variable should also be checked for initialization to avoid a warning or error (depending on settings):
isset($stringvar)
This results in the more acceptable:
if (isset($stringvar) && $stringvar !== '') {
}
PHP has a lot of bad conventions. I originally answered this (over 9 years ago) using the empty() function, as seen below. I've long since abandoned PHP, but since this answer attracts downvotes and comments every few years, I've updated it. Should the OP wish to change the accepted answer, please do so.
Original Answer:
if(empty($stringvar))
{
// do something
}
You could also add trim() to eliminate whitespace if that is to be considered.
Edit:
Note that for a string like '0', this will return true, while strlen() will not.
You need isset() in case $str is possibly undefined:
if (isset($str) && $str !== '') {
// variable set, not empty string
}
Using !empty() would have an important caveat: the string '0' evaluates to false.
Also, sometimes one wants to check, in addition, that $str is not something falsy, like false or null[1]. The previous code doesn't handle this. It's one of the rare situations where loose comparison may be useful:
if (isset($str) && $str != '') {
// variable set, not empty string, not falsy
}
The above method is interesting as it remains concise and doesn't filter out '0'. But make sure to document your code if you use it.
Otherwise you can use this equivalent but more verbose version:
if (isset($str) && (string) $str !== '') {
// variable set, not empty string, not falsy
}
Of course, if you are sure $str is defined, you can omit the isset($str) from the above codes.
Finally, considering that '' == false, '0' == false, but '' != '0', you may have guessed it: PHP comparisons aren't transitive (fun graphs included).
[1] Note that isset() already filters out null.
This will safely check for a string containing only whitespace:
// Determines if the supplied string is an empty string.
// Empty is defined as null or containing only whitespace.
// '0' is NOT an empty string!
function isEmptyString($str) {
return !(isset($str) && (strlen(trim($str)) > 0));
}
What about this:
if( !isset($str[0]) )
echo "str is NULL or an empty string";
I found it on PHP manual in a comment by Antone Roundy
I posted it here, because I did some tests and it seems to work well, but I'm wondering if there is some side effect I'm not considering. Any suggestions in comments here would be appreciated.
According to PHP empty() doc (http://ca1.php.net/empty):
Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.
This simple old question is still tricky.
strlen($var) works perfectly ONLY if you're absolutely sure the $var is a string.
isset($var) and empty($var) result are based on type of the variable, and could be tricky at some cases (like empty string ""). View the table in this page for more details.
UPDATE
There are actually 2 cases for this question:
Case 1: You're sure that your variable is always going to be a "string":
In this case, just test the length:
if(strlen($str) > 0) {
// do something..
}
Case 2: Your variable may and may not be a "string":
In this case, it depends on what you want to do. For me (most of the time), if it's not a string then I validate it as "false". You can do it this way:
if(is_string($var) && $var !== '') {// true only if it's a string AND is not empty
// do something ...
}
And to make it shorter and in 1 condition instead of 2 (specially useful if you're testing more than 1 string in same if condition), I made it into function:
function isNonEmptyString($var) {
return is_string($var) && $var !== '';
}
// Somewhere else..
// Reducing conditions to half
if(isNonEmptyString($var1) && isNonEmptyString($var2) && isNonEmptyString($var3)) {
// do something
}
If your variable $str is not defined then your strlen() method will throw an exception. That is the whole purpose of using isset() first.
trimming the string will also help if there are string with white spaces.
if (isset($str) && trim($str) !== '') {
// code
}
I think not, because strlen (string lenght) returns the lenght (integer) of your $str variable.
So if the variable is empty i would return 0. Is 0 greater then 0. Don't think so.
But i think the first method might be a little more safer. Because it checks if the variable is init, and if its not empty.