PHP problem, I'm sure this has an easy solution, just can't see it
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" || "attrNa开发者_运维百科me") {
$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
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.
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"));
Try this as a shorter version of Iznogood's answer:
if (in_array($fieldName, array("brandName", "oeNumber", "articleId", "quantityPerPackingUnit", "attrName")))
精彩评论