Can boolean needle be passed to in_array? - php

Can I pass false as a needle to in_array()?
if(in_array(false,$haystack_array)){
return '!';
}else{
return 'C';
}
The $haystack_array will contain only boolean values. The haystack represents the results of multiple write queries. I'm trying to find out if any of them returned false, and therefore not completed.

PHP won't care what you pass in as your 'needle', but you should probably also use the third (optional) parameter for in_array to make it a 'strict' comparison. 'false' in PHP will test as equal to 0, '', "", null, etc...

Yep, just like in your example code. Because in_array returns a boolean to indicate whether the search was successful (rather than returning the match), it won't cause any problems.

There's got to be a better way.
<?php
echo (in_array(false,array(true,true,true,false)) ? '!' : 'C');
echo (in_array(false,array(true,true,true,true)) ? '!' : 'C');
Output:
!C

Yes you can but why don't you do it with a single boolean variable like this:
$anyFalseResults = false;
... your query loop {
// do the query
if( $queryResult == false ) $anyFalseResults = true;
}
at the end of the loop $anyFalseResults will contain what you are looking for.

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

Unable to get the position of a character within my string using strpos

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

PHP in_array issue while checking zero value in array giving true

I am facing one strange situation while working with PHP's in_array(). Below is my code and its output
<?php
$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
if(!in_array(0, $process))
echo "success";
else
echo "not success";
//It's outputting "not success";
var_dump(in_array(0, $process));
//Output : null
var_dump(in_array(0, $this->tProcessActions) === true);
///Output : true
If we look at the $process array, there is no 0 value in it. Still it's giving me true if I check if(in_array(0, $process))
Can anybody has idea about it?
If you need strict checks, use the $strict option:
in_array(0, $process, true)
PHP's string ⟷ int comparison is well known to be complicated if you don't know the rules/expect the wrong thing.
Try like
if(!in_array('0', $process)) {
or you can use search(optional) like
if(array_search('0',$process)) {
I believe you should put 0 inside the quotes:
if(!in_array("0", $process))
I think because in_array maybe not strict type check. because if you check
if (0 == "deleted") echo "xx";
Try this
if(!in_array('0', $process))
using the strict parameter gives what you want here:
$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
var_dump( in_array(0, $process, true ) );
// gives false
or use array_search and test if non-false;
var key = array_search( 0, array( 'foo' => 1, 'bar' => 0 ) );
// key is "bar"
You need use third parameter [$is_strict] of in_array function.
in_array(0, $process, true)
The point is what any string after (int) conversion equal to 0.
(int) "deleted" => 0.
So in_array without strict mode is equal to "deleted" == 0 which true. When you use strict its equal to "deleted" === 0 which false.

PHP Count Number of True Values in a Boolean Array

I have an associative array in which I need to count the number of boolean true values within.
The end result is to create an if statement in which would return true when only one true value exists within the array. It would need to return false if there are more then one true values within the array, or if there are no true values within the array.
I know the best route would be to use count and in_array in some form. I'm not sure this would work, just off the top of my head but even if it does, is this the best way?
$array(a->true,b->false,c->true)
if (count(in_array(true,$array,true)) == 1)
{
return true
}
else
{
return false
}
I would use array_filter.
$array = array(true, true, false, false);
echo count(array_filter($array));
//outputs: 2
Array_filter will remove values that are false-y (value == false). Then just get a count. If you need to filter based on some special value, like if you are looking for a specific value, array_filter accepts an optional second parameter that is a function you can define to return whether a value is true (not filtered) or false (filtered out).
Since TRUE is casted to 1 and FALSE is casted to 0. You can also use array_sum
$array = array('a'=>true,'b'=>false,'c'=>true);
if(array_sum($array) == 1) {
//one and only one true in the array
}
From the doc : "FALSE will yield 0 (zero), and TRUE will yield 1 (one)."
Try this approach :
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Result :
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
Documentation
like this?
$trues = 0;
foreach((array)$array as $arr) {
$trues += ($arr ? 1 : 0);
}
return ($trues==1);
Have you tried using array_count_values to get an array with everything counted? Then check how many true's there are?

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

Categories