Reputation: 746
I am trying to use PHP's strpos()
function to search for a string within another string. I have performed 2 different searches, both containing a colon character. The only difference I can see between the two is whether the colon appears at the beginning of the 'needle' or the end.
My code is as follows:
<?php
$string = 'abc:def';
echo strpos($string,'abc:') ? 'abc: true' : 'abc: false';
echo ' / ';
echo strpos($string,':def') ? ':def true' : ':def false';
The output I am getting is abc: false / :def true
. I don't understand why, and was hoping someone can explain it to me. You can see a working example here:
Upvotes: 0
Views: 452
Reputation: 1580
Strpos returns the position of a given string (needle) in other string (stack). See reference - strpos. Correct usage of strpos (notice it's !==
not !=
, since we want to also check for type):
$string = 'abc:def';
echo strpos($string,'abc:') !== false ? 'abc: true' : 'abc: false';
echo ' / ';
echo strpos($string,':def') !== false ? ':def true' : ':def false';
Summing up, strpos returns the numeric value that is a position (so for example 0 or 5) or false
when the value is not found.
As to why your snippet
echo strpos($string,':def') ? ':def true' : ':def false';
returns true - in PHP every non-zero integer is treated as true
, if you are comparing it as boolean, and your strpos returned value bigger than zero (probably '4' in this example), so it was considered true
. See here for more details.
Upvotes: 2
Reputation: 44844
You need to use Boolean comparison and it returns false only when there is no match
$string = 'abc:def';
echo strpos($string,'abc:') !== false ? 'abc: true' : 'abc: false';
echo ' / ';
echo strpos($string,':def') !== false ? ':def true' : ':def false';
strpos($string, "abc") will return (int) 0
(int) 0 !== false ---> true statement
(int) 0 === true ---> false statement
Upvotes: 1
Reputation: 13728
In your case strpos() returning true/false
result so you need to check according to return result
try
echo strpos($string,'abc:') !== false ? 'abc: true' : 'abc: false';
echo ' / ';
echo strpos($string,':def') !== false ? ':def true' : ':def false';
Upvotes: 1
Reputation: 9351
as per doc
strpos()
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.
so
strpos($string,'abc:')
is returning 0. so it is echoing :
abc: false
Upvotes: 1