Search code examples
phpforeachstrpos

Loose truthy comparison on return value from strpos() gives opposite expected result


I know the $a variable with the tag is not properly formatted, however that's irrelevant to the issue.

The issue is that strpos is looking for a forward slash, /, in the value of each key in the array, but it is not printing.

$a = '<a target="" href="/test/url">test';
$a_expanded = explode("\"", $a);
echo print_r($a_expanded);
foreach($a_expanded as $num => $aspect) {
  echo $aspect;
  if ($contains_path = strpos($aspect, '/')) {
    echo $a_expanded[$num];
  }
}

It echos the array and each aspect, but will not echo the string with the forward slashes when found by strpos.


Solution

  • strpos() could either return FALSE, 0, or a non-zero value.

    • If the needle occurs at the beginning of the haystack, strpos() returns 0.
    • If it occurs elsewhere, it returns the respective position of the needle in the haystack.
    • If needle wasn't found in the haystack, strpos() returns boolean FALSE.

    I wasn't checking for strict equality, so the if statement always returned a falsey value, causing my code to not work.

    if ($contains_path = strpos($aspect, '/'))
    

    To fix the issue, you could use !==, which compares the type and value:

    if ($contains_path = (strpos($aspect, '/') !== FALSE))
    

    For more information, check the following links: