We help IT Professionals succeed at work.

PHP Checking a variable

Robert Granlund
on
Is there a way to check if a variable contains a value, without it matching exactly?

Meaning, I have the following line of code:
<?php
if (!empty($error_status['ExtendedStatusCd']) && $error_status['ExtendedStatusCd'] == "OFAC Hit, Score:100.00")

Open in new window

However, I would like it to check if it has "OFAC Hit"  not the rest.  Something like this:
<?php
if (!empty($error_status['ExtendedStatusCd']) && $error_status['ExtendedStatusCd'] == "OFAC Hit%")

Open in new window

Comment
Watch Question

Marco GasiFreelancer
Top Expert 2010

Commented:
Use strpos:

$pos = strpos($error_status['ExtendedStatusCd', "OFAC Hit"]); 
if (!empty($error_status['ExtendedStatusCd']) && $pos  !== false )

Open in new window

Marco GasiFreelancer
Top Expert 2010

Commented:
Learn here about http://php.net/strpos
Commented:
Solution #1 - using regular expression match:
$regexMatch = preg_match("/^(OFAC Hit).+/", $error_status['ExtendedStatusCd']) ? true : false;
if (!empty($error_status['ExtendedStatusCd']) && $regexMatch)

Open in new window


Solution #2 - matching against part of the string:
$matchSubstring = substr($error_status['ExtendedStatusCd'], 0, 8) == "OFAC Hit" ? true : false;
if (!empty($error_status['ExtendedStatusCd']) && $matchSubstring)

Open in new window

Chris Harte2015 Top Expert (Most Article Points)

Commented:
I would have thought strstr() would be more suitable

http://php.net/manual/en/function.strstr.php

if (!empty($error_status['ExtendedStatusCd'])
     && strstr ($error_status['ExtendedStatusCd'], "OFAC Hit"))

Open in new window

Marco GasiFreelancer
Top Expert 2010

Commented:
Ooops, sorry rgranlund, I mystyped the statement:
$pos = strpos($error_status['ExtendedStatusCd'], "OFAC Hit"); 
if (!empty($error_status['ExtendedStatusCd']) && $pos  !== false )

Open in new window


Glad you have solved anyway :-)