Creating a New Variable Based On a Matched Array ID Value [duplicate] - php

<?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

why does in_array return true when a value only begins with what is in an array

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";
}

Why does php in_array return true for an unmatched string value? Is this a bug? [duplicate]

I have found some odd behaviour while I was using the PHP function in_array(). I have an array like this:
$arr = [TRUE, "some string", "something else"];
Now if I want to check if "test" is in the array it is clearly not, but in_array() still returns TRUE, why is that?
$result = in_array("test", $arr);
var_dump($result); //Output: bool(true)
The same thing happens when using array_search():
$result = array_search("test", $arr);
var_dump($result); //Output: int(0)
I thought maybe that the value TRUE in the array was automatically causing the function to return TRUE for every result without checking the rest of the array, but I couldn't find any documentation that would suggest that very odd functionality.
This behaviour of the function in_array() and array_search() is not a bug, but instead well documented behaviour.
Both functions have a 3rd optional parameter called $strict which by default is FALSE:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
Now what that means is that by default both functions use loosely(==) comparison to compare the values. So they only check if the values are the same after PHP type juggling and without checking the type. Because of that in your example TRUE == "any none emtpy string" evaluates to TRUE.
So by setting the 3rd parameter to TRUE while calling the function you say that PHP should use strict(===) comparison and it should check value AND type of the values while comparing.
See this as a reference: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
You are right, the boolean can indeed cause this. Set the strict flag in the in_array function, this way also the type of the element is checked (basically the same as using ===):
if (in_array("username", $results, true)) // do something
if (in_array("password", $results, true)) // do something
if (in_array("birthday", $results, true)) // do something

PHP strpos to match querystring text pattern

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

Finding common characters in strings

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

How to check if a string is one of the known values?

<?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.

Categories