iPixel Posted August 21, 2012 Share Posted August 21, 2012 I've got a field, it get's passed to this php page. That field passes data that looks like so: MC#1. This is some regular text, no big deal. MA#2. Some more text, again no big deal Here's my script: <?php $test_data = explode("\n\n", $test_data); foreach($test_data as $text=> $value) { if(strpos($value,'MC#')) { echo $value; //Note: $values echoed value = "MC#1. This is some regular test, no big deal." } else { echo "<br />Did not find MC#<br />"; } } ?> My Issue, is that the "IF" always fails. Clearly $value has MC# in the string but still doesn't find it. I've also tried if(strpos($value,'MC#') === true) and other variations of the two. But no luck, for each $test_data it never finds MC#. I'm sure i'm missing something. However, i have no clue what. Thanks! Link to comment https://forums.phpfreaks.com/topic/267383-why-isnt-my-strpos-working/ Share on other sites More sharing options...
scootstah Posted August 21, 2012 Share Posted August 21, 2012 The problem is that strpos() is returning 0 (because that is the position of the match), which PHP is interpreting as "false" (because PHP is a loosely-typed language). You tried if (strpos() === true), but that won't work because strpos() never returns boolean true. It only returns the position (if found) or boolean false (if not found). So, the solution is thus: if (strpos($value, 'MC#') === 0) { EDIT: Actually, if you want to check if "MC#" exists anywhere in the string, you can go with: if (strpos($value, 'MC#') !== false) { Link to comment https://forums.phpfreaks.com/topic/267383-why-isnt-my-strpos-working/#findComment-1371163 Share on other sites More sharing options...
iPixel Posted August 21, 2012 Author Share Posted August 21, 2012 Doh! I guess i misunderstood it. I just figured that if strpo($value,"MC#") returned anything the if statement would go through. I guess 0 is a no no . Thanks very much for the explanation. Link to comment https://forums.phpfreaks.com/topic/267383-why-isnt-my-strpos-working/#findComment-1371164 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.