tags:

views:

83

answers:

3

Hi all, I am new to php and this little bugger has been eating up my day, perhaps it's due to some property of php I am unaware of?

As part of some code for getting some data out of an xml file (using the event based Expat parser), I have the following code

$xmlFields;
$fieldName = "";

............... some other code ............

function char($parser,$data)
{

    global $xmlFields, $fieldName;

    if($fieldName) {
        if($fieldName == "brandName" || "oeNumber" || "articleId" || "quantityPerPackingUnit" || "attrName") {
             $xmlFields[$fieldName] = $data;
             echo $data;
        } 
    }
}

I try to echo $xmlFields["brandName"] for example, and nothing is printed.

1) I know that $xmlFields["brandName"] is non-empty because echo $data actually returns something.

2) If I change to $xmlFields[$fieldName] = 'some string'; then echo $xmlFields["brandName"] will print 'some string'

so why won't it print $xmlFields["brandName"]?

Thanks in advance, Yazan

+7  A: 

You cannot link ORs like that. try

    if($fieldName == "brandName" || $fieldName =="oeNumber" || $fieldName =="articleId" || $fieldName =="quantityPerPackingUnit" || $fieldName == "attrName") {

As Deceze said a much better option when you are searching in an array is to use

if (in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName")))

I know some languages allow such construct but php is not one of them.

Iznogood
+3  A: 

Try this as a shorter version of Iznogood's answer:

if (in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName")))
deceze
+4  A: 

The following expression

$fieldName == "brandName" || "oeNumber" || "articleId" || "quantityPerPackingUnit" || "attrName"

is parsed as

(
  (
    (
      ($fieldName == "brandName") || ("oeNumber")
    ) || ("articleId")
  ) || ("quantityPerPackingUnit")
) || ("attrName")

Notice that your equality check is separated from the other checks. In this case, the expression always evaluates to true.

You can use an array for this case:

in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName"));
strager
+1 for explaining what's actually happening in OP's code.
BoltClock
Thank you all, you're comments were very helpful. Problem solved.