How to find if a string contains a specific integer php - php

I have a variable that outputs as 0 type int
I have another string that outputs as 0,1,2.
I am trying to find out if the string contains that very integer, both of these are dynamic values and being fetched from database.
I have tried -
if (strpos($string, $int) !== false) {
echo 'true';
}
But it is not working.

You can use type conversion:
if (strpos($string, (string) $int) !== false)
echo 'true';

Related

PHP Conditional to see if string contains a variable [duplicate]

This question already has answers here:
Problem with Strpos In PHP
(3 answers)
PHP strpos() function returning incorrect result
(1 answer)
Closed 5 years ago.
I'm struggling to figure out how to use PHP strpos to find a variable in a string. The code below works if I enter a number directly but not if I replace the number with a variable I know to be a single number. No PHP errors present but the conditional renders false. I've been searching all over and am stumped by this.
The $string variable returns "253,254,255".
The $current_page_id variable returns "253".
$string = "";
foreach( $page_capabilities as $post):
$string .= $post->ID.',';
endforeach;
if (strpos($string, $current_page_id) !== false) {
// This works
//if (strpos($string, '253') !== false) {
// This does not
if (strpos($string, $current_page_id) !== false) {
echo 'true';
}
}
You don't need that CSV string to check for the ID you're looking for. You can just do it in the foreach loop where you're currently building the string.
foreach ($page_capabilities as $post) {
if ($post->ID == $current_page_id) {
echo 'true';
break; // stop looking if you find it
}
}
You should cast $current_page_id to a string:
if (strpos($string, (string)$current_page_id) !== false) { ...
The following is from php docs:
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
Which means you were comparing "253,254,255" with the character corresponding to 253 in the ASCII table
You need to cast the integer to a string.
$postIDs = [55, 89, 144, 233];
$string = implode(',', $postIDs);
$postID = 55;
if(strpos($string, strval($postID)) !== false) {
echo 'strpos did not return false';
}
I would suggest you to change your approach. You should search for the exact string value. Because as #mickmackusa suggested, it would find 25 & 53 too
$page_capabilities = array(array('POSTID' => 253),array('POSTID' => 254),array('POSTID' => 255));
$current_page_id = '255';
$key = array_search($current_page_id, array_column($page_capabilities, 'POSTID'));
if($key !== false) {
echo 'true';
}

How to detect the presence of a given number in a string

I need to verify the presence of a number in a string. This is the code I had used:
$line='1';
$a=1;
echo strpos($line, $a);
if (strpos($line, 1) !== false) {
echo 'ok';
}
I also tried this:
$line='1';
$a=1;
echo strpos($line, $a);
if (strpos($line, 1+'0') !== false) {
echo 'ok';
}
In either case, however, it doesn't work.
From the documentation:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Since you're passing 1 as the needle, it's being converted to the character with that code, i.e. Control-A. So it's not looking for the digit 1 in the string. If you want to look for the character 1, you have to use a character string, not an integer:
$a = '1';
echo strpos($line, $a);
if(strpos($line, '1') !== false) {
echo 'ok';
}
If you're initially given a number, you can convert it to a string with strval():
$a = 1;
$a = strval($a);
echo strpos($line, $a);
if(strpos($line, $a) !== false) {
echo 'ok';
}
The strpos works on strings. If you do this
$line='1234';
$a='1';
echo strpos($line, '1');
if(strpos($line, '1') !== false){
echo 'ok';
}
or
$line='1234';
$a='1';
echo strpos($line, $a);
if(strpos($line, $a) !== false){
echo 'ok';
}
It will work
strpos takes three arguments where third argument is optional i.e
strpos(string,find,start). Here find should be of string type if it is not of string type then it is converted to an integer and applied as the ordinal value of a character. Means it takes its ascii value character. For eg.
$string="ABC";
$find=65;
$pos=strpos($string,$find);
echo $pos
Output:
0
i.e position of character 'A' because 65 is an ASCII value of 'A' character.
So when you passed integer value 1 to the strpos function it is converted to some ASCII character and it will return false in your case.
It might be possible that strpos function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. So, use the === operator for testing the return value of this function.
To work your code fine you have to convert the integer type to string type.
maybe you can use the php function ord(), and check if the number is in the range of a ASCII for the numbers.

Search php string - %like% sql

Right now I use stristr($q, $string) but if
$string = "one monkey can jump 66 times";
$q = "monkey 66";
I want to find out if this string contains both monkey and 66.
How can i do that?
you could use both stristr and strpos.
as it is reported in this post, the second method is faster and less memory intensive.
well, check this lines out:
// here there are your string and your keywords
$string = "one monkey can jump 66 times";
$q = "monkey 66";
// initializate an array from keywords in $q
$q = explode(" ", $q);
// for every keyword you entered
foreach($q as $value) {
// if strpos finds the value on the string and return true
if (strpos($string, $value))
// add the found value to a new array
$found[] = $value;
}
// if all the values are found and therefore added to the array,
// the new array should match the same object of the values array
if ($found === $q) {
// let's go through your path, super-man!
echo "ok, all q values are in string var, you can continue...";
}
if(stristr('monkey', $string) && stristr('66', $string)) {
//Do stuff
}
simply post your variable value by giving them a variable $monkey,$value ($monkey jumps $value) and then fetch its value
You can use the strpos() function which is used to find the occurrence of one string inside another one:
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
echo 'true';
}
Note that the use of !== false is deliberate (neither != false nor === true will work); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').

simple strpos() not working with "[" char, why?

why does if i do:
if(strpos("[","[rgeger]")){
echo 'hey';
}
it doesn't prints anything?
try this with a string:
function return_tags($keywords){
if($keywords){
$k_array = array();
foreach($this->check($keywords) as $key=>$value){
array_push($k_array, $value);
}
$last_array = array();
foreach($k_array as $key=>$value){
if(strpos("[", $value) && strpos("]", $value) && strlen($value) >= 2){
$value = '<span class="tag">'.$value.'</span>';
}
array_push($last_array, trim($value));
}
return $last_array;
}else{
return false;
}
}
string example
$keywords = "freignferi eiejrngirj erjgnrit [llll] [print me as tag]";
did you see any <span> element printed in html?
It looks like you swapped the arguments:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
So if you want to know if a [ is in your string [rgeger]:
if (strpos("[rgeger]", "[") !== false) {
echo 'hey';
}
(Source: http://php.net/strpos)
The position returned is zero-indexed, so the first character is at position 0. When evaluating 0 as Boolean, it's false - so it doesn't get into the block.
Fix with this:
if (strpos('[rgeger]', '[') !== false)
Also the arguments are the wrong way round. Don't upvote this post any more; go upvote robbi's instead for spotting that one :) Eagle eyes robbi, EAGLE eyes :P
Because you have to check the return value of strpos() as it could be zero because [ it's at index zero, and zero evaluates to FALSE that's why it wouldn't enter your if block, so check that the return value it's FALSE and type boolean, not just integer zero, like this:
if(strpos("[rgeger]","[") !== false){
echo 'hey';
}
UPDATE:
The parameters were in wrong order too, the subject string comes first then the search string, I updated my code above to reflect that.
Because its wrong. Strpos give false if the condition is false.
if(strpos("[rgeger]","[") !== false){
echo 'hey';
}
Edit: I have corrected my answer. Your parameter are in the wrong order. Its:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Because actually strpos can return 0 see doc.
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 you have to compare with the falsevalue directly.
if(strpos("[","[rgeger]") !== false){
echo 'hey';
}
EDIT ::
Careful.. Look at the arguments order
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Haystack is the string input.
Needle is what you are seeking for.
if(strpos("[regeger]","[") !== false){
echo 'hey';
}

Why does (0 == 'Hello') return true in PHP?

Hey, if you have got the following code and want to check if $key matches Hello I've found out, that the comparison always returns true if the variable is 0. I've came across this when an array for a special key and wondered why it's wasn't working as expected.
See this code for an example.
$key = 1;
if ($key != 'Hello') echo 'Hello'; //echoes hello
$key = 2;
if ($key != 'Hello') echo 'Hello'; //echoes hello
$key = 0;
if ($key != 'Hello') echo '0Hello'; //doesnt echo hello. why?
if ($key !== 'Hello') echo 'Hello'; //echoes hello
Can anyone explain this?
The operators == and != do not compare the type. Therefore PHP automatically converts 'Hello' to an integer which is 0 (intval('Hello')). When not sure about the type, use the type-comparing operators === and !==. Or better be sure which type you handle at any point in your program.
Others have already answered the question well. I only want to give some other examples, you should be aware of, all are caused by PHP's type juggling. All the following comparisons will return true:
'abc' == 0
0 == null
'' == null
1 == '1y?z'
Because i found this behaviour dangerous, i wrote my own equal method and use it in my projects:
/**
* Checks if two values are equal. In contrast to the == operator,
* the values are considered different, if:
* - one value is null and the other not, or
* - one value is an empty string and the other not
* This helps avoid strange behavier with PHP's type juggling,
* all these expressions would return true:
* 'abc' == 0; 0 == null; '' == null; 1 == '1y?z';
* #param mixed $value1
* #param mixed $value2
* #return boolean True if values are equal, otherwise false.
*/
function sto_equals($value1, $value2)
{
// identical in value and type
if ($value1 === $value2)
$result = true;
// one is null, the other not
else if (is_null($value1) || is_null($value2))
$result = false;
// one is an empty string, the other not
else if (($value1 === '') || ($value2 === ''))
$result = false;
// identical in value and different in type
else
{
$result = ($value1 == $value2);
// test for wrong implicit string conversion, when comparing a
// string with a numeric type. only accept valid numeric strings.
if ($result)
{
$isNumericType1 = is_int($value1) || is_float($value1);
$isNumericType2 = is_int($value2) || is_float($value2);
$isStringType1 = is_string($value1);
$isStringType2 = is_string($value2);
if ($isNumericType1 && $isStringType2)
$result = is_numeric($value2);
else if ($isNumericType2 && $isStringType1)
$result = is_numeric($value1);
}
}
return $result;
}
Hope this helps somebody making his application more solid, the original article can be found here:
Equal or not equal
pretty much any non-zero value gets converted to true in php behind the scenes.
so 1, 2,3,4, 'Hello', 'world', etc would all be equal to true, whereas 0 is equal to false
the only reason !== works is cause it is comparing data types are the same too
Because PHP does an automatic cast to compare values of different types. You can see a table of type-conversion criteria in PHP documentation.
In your case, the string "Hello" is automatically converted to a number, which is 0 according to PHP. Hence the true value.
If you want to compare values of different types you should use the type-safe operators:
$value1 === $value2;
or
$value1 !== $value2;
In general, PHP evaluates to zero every string that cannot be recognized as a number.
In php, the string "0" is converted to the boolean FALSE http://php.net/manual/en/language.types.boolean.php

Categories