<?php
$a = 'abc';
if($a among array('are','abc','xyz','lmn'))
echo 'true';
?>
Suppose I have the code above, how to write the statement "if($a among...)"?
Use the in_array() function.
Manual says:
Searches haystack for needle using loose comparison unless strict is set.
Example:
<?php
$a = 'abc';
if (in_array($a, array('are','abc','xyz','lmn'))) {
echo "Got abc";
}
?>
Like this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
echo 'True';
}
Also, although it's technically allowed to not use curly brackets in the example you gave, I'd highly recommend that you use them. If you were to come back later and add some more logic for when the condition is true, you might forget to add the curly brackets and thus ruin your code.
There is in_array function.
if(in_array($a, array('are','abc','xyz','lmn'), true)){
echo 'true';
}
NOTE:
You should set the 3rd parameter to true to use the strict compare.
in_array(0, array('are','abc','xyz','lmn')) will return true, this may not what you expected.
Try this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
// Code
}
http://php.net/manual/en/function.in-array.php
in_array — Checks if a value exists in an array
bool in_array ( mixed $needle , array $haystack [, bool $strict =
FALSE ] ) Searches haystack for needle using loose comparison unless
strict is set.
Related
I've noticed a strange thing about PHP's in_array function. For some reason, it will only check if the first character(s) of the needle match with any of the values of the haystack - as opposed to if the whole needle is in the haystack.
For example, in a situation where $string equals 1thisisatest, the following script will return In array.
$allowed = [0, 1];
if(in_array($string, $allowed)){
echo "In array";
} else {
echo "Not in array";
}
Whereas if $string equals 2thisatest, the script will return Not in array.
Now either this is a bug, or a very strange feature. Wouldn't you want it to check needles against the haystack exactly as they appear?
If this is, indeed, how the function is supposed to work, how does one go about getting the intended result without iterating over every single element in the array? Seems kind of pointless.
EDIT:
Some of you are saying to use strict mode. This is all fine and dandy, until you checking against $_GET data, which is always a string. So the following will return false:
$value = $_GET["value"]; // this returns "1"
in_array($value, [0, 1], true)
Because the in_array function uses the == operator. Thus 1 == "1thisisatest" - so, in_array will return true.
To fix this you can enabled strict mode:
// in the third parameter (to use === instead of ==)
in_array($search_value, $array_name, true)`
in_array by default uses == which will follow the rules of type juggling
The solution is to use strict comparison:
in_array($value, [0, 1], true);
If you are concerned about $_GET variables you need to ensure you always validate and sanitize your input before using it otherwise you might end up with strange results:
$value = filter_input(INPUT_GET, 'value', FILTER_VALIDATE_INT);
in_array($value, [0, 1], true);
It is always good to validate and sanitize your input to avoid things like e.g. someone calling your URL as ?value[]=1 which will mean $_GET['value'] will be an array causing (most likely) errors in the best case and strange undocumented behaviour in the worst case.
Make $allowed an array of strings and use strict mode.
$allowed = ["0", "1"];
if (in_array($_GET['value'], $allowed, true)) {
echo "In array";
} else {
echo "Not in array";
}
If you need to be more accurate you have to put the boolean true in your function like this:
$string = "1thisisatest";
$allowed = array(0, 1);
if(in_array($string, $allowed, true)){
echo "In array";
} else {
echo "Not in array";
}
<?php
$a = 'abc';
if($a among array('are','abc','xyz','lmn'))
echo 'true';
?>
Suppose I have the code above, how to write the statement "if($a among...)"?
Use the in_array() function.
Manual says:
Searches haystack for needle using loose comparison unless strict is set.
Example:
<?php
$a = 'abc';
if (in_array($a, array('are','abc','xyz','lmn'))) {
echo "Got abc";
}
?>
Like this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
echo 'True';
}
Also, although it's technically allowed to not use curly brackets in the example you gave, I'd highly recommend that you use them. If you were to come back later and add some more logic for when the condition is true, you might forget to add the curly brackets and thus ruin your code.
There is in_array function.
if(in_array($a, array('are','abc','xyz','lmn'), true)){
echo 'true';
}
NOTE:
You should set the 3rd parameter to true to use the strict compare.
in_array(0, array('are','abc','xyz','lmn')) will return true, this may not what you expected.
Try this:
if (in_array($a, array('are','abc','xyz','lmn')))
{
// Code
}
http://php.net/manual/en/function.in-array.php
in_array — Checks if a value exists in an array
bool in_array ( mixed $needle , array $haystack [, bool $strict =
FALSE ] ) Searches haystack for needle using loose comparison unless
strict is set.
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.
I need to execute a bit of script only if the $_GET['page'] parameter has the text "mytext-"
Querystring is: admin.php?page=mytext-option
This is returning 0:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
echo $match;
strpos returns the position of the string. Since it's 0, that means it was found at position 0, meaning, at the start of the string.
To make an easy way to understand if it's there, add the boolean === to an if statement like this:
<?php
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match === false ) {
echo 'Not found';
} else {
echo 'Found';
}
?>
This will let you know, if the string is present or not.
Or, if you just need to know, if it's there:
$myPage = $_GET['page'];
$match = strpos($myPage, 'mytext-');
if ( $match !== false ) {
echo 'Found';
}
?>
Use substr() once you get the location of 'mytext-', like so:
$match = substr($myPage, strpos( $myPage, 'mytext-') + strlen( 'mytext-'));
Otherwise, strpos() will just return the numerical index of where 'mytext-' starts in the string.
You can also use str_replace() to accomplish this if your string only has 'mytext-' once:
$match = str_replace( 'mytext-', '', $myPage);
The function strpos() returns the position where the searched string starts which is 0. If the string is not found, the function will return false. See the strpos documentation which tells you as well:
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.
A solution to your question would be to use substr(), preg_match() or check if strpos() !== false.
The easiest solution should be this:
if (preg_match('/^mytext-/i', $_GET['page'])) {
// do something
}
You may also consider using more than just one GET parameter like
http://www.example.com/foo.php?page=mysite&option1=123&option2=456
You then use your parameters lik $_GET['page'], $_GET['option1'], $_GET['option2'], etc.
However, you should also be careful what you do with raw $_GETor $_POST data since users can directly input them and may inject harmful code to your website.
That is expected since the substring starts at index 0. Read the warning on php.net/strpos:
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.
If you only need to check if $myPage contains 'mytext-', use stristr:
if(stristr($myPage, 'mytext-') !== false) {
// contains..
}
What's wrong about preg_match?
$myPage = $_GET['page'];
if (preg_match("/\bmytext-\b/i", $myPage)) {
//Do Something
}
Or do you need the "option" out of "mytext-option"?
If yes you can use this:
$myPage = $_GET['page'];
$querystrings = explode("-", $myPage);
if ($querystrings[0] == 'mytext')) {
//Do Something
echo $querystrings[1]; //outputs option
}
With this you can even use more "options" in your querystring like "mytext-option-whatever". That's the same as when you use
$_GET['page'], $_GET['option'], $_GET['whatever']
when you use
?page=mysite&option=x&whatever=y
I am tring this method to find the common characters in two strings namely, $a and $r, but the first character isn't getting printed . Moreover the $already collects the common characters and prevents them from being printed for multiple times( I need each character to be printed once only) but it isn't doing so. Please tell me what errors I am making.
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$already="";
for($i=0;$i<strlen($r);$i++)
{
if (stripos($a,$r[$i])!=FALSE)
{
if (stripos($already,$r[$i])==FALSE)
{
$already=$already.$r[$i];
echo "already=".$already."<br>";
echo $r[$i]."<br>";
}
}
}
?>
Use !==FALSE instead of !=FALSE. The problem is that stripos returns 0 if the needle is at the start of the haystack, and 0 is falsy. By using !== you are forcing it to ensure the result is actually false, and not just 0.
This is actually listed in the docs. An "RTM" might be appropriate here.
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.
The simplest way to find the intersection of the two strings in PHP is to turn them into arrays and use the built-in functions for that purpose.
The following will show all the unique and common characters between the two strings.
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$a_arr = str_split($a);
$r_arr = str_split($r);
$common = implode(array_unique(array_intersect($a_arr, $r_arr)));
echo "'$common'";
?>
I would think a much simpler solution to this would be to make the strings into arrays and compare those no?
Something like:
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$shared = implode( '' , array_intersect( str_split($a) , str_split($r) ) );
?>
That should return you a string of all the characters in $a that are present in $r