...

View Full Version : Resolved Why is this conditional statement not evaluating like I expect it too?



BMAN99
07-29-2012, 02:39 AM
Hey guys,

I'm a bit stumped on this one. I would have expected the following code to echo "string contains either 123 or abc". But it doesn't! Any idea why?



<?php

$string = "123 abc";

$needle = strpos($string, "123");
$needle2 = strpos($string, "def");

if (($needle === true) || ($needle2 === true)) {
echo "string contains either 123 or abc";
} else {
echo "string does NOT contain either 123 or abc";
}

?>


Am I doing something wrong? Or is there a better way to check whether a string contains either of two specific substrings?

tracknut
07-29-2012, 03:16 AM
If it finds the string, strpos returns the position of the string, not "true". So you could test != false, but I don't think it will ever return "true".


if (strpos($string, "123") || strpos($string, "def")) {
...


Dave

Inigoesdr
07-29-2012, 04:29 AM
tracknut is mostly correct. strpos() (http://php.net/strpos) won't ever return an explicit TRUE. It will be FALSE or a number. So, your conditions should look more like this:

$needle = strpos($string, "123");
$needle2 = strpos($string, "def");

if ($needle !== false || $needle2 !== false) {
echo "string contains either 123 or abc";
} else {
echo "string does NOT contain either 123 or abc";
}
You want to test for explicit, "!==", not false because with PHP's loose type conversion if the substring position is 0(at the beginning of the string) it will evaluate to false with "!=" and your result will be incorrect.

BMAN99
07-29-2012, 02:02 PM
Thanks guys! :) That makes sense.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum