Page 1 of 1

Help a PHP newbie with strings/arrays/xml?

Posted: Thu Jul 15, 2004 6:57 pm
by stsr11
I am very new to PHP, although not so new to programming and would appreciate a little help on the following:

My PHP app (my first) reads an XML file, parses it and feeds it into an array...that all works fine.

My problem is trivial and can be sorted with extra coding - I just wondered if anyone knew of an elegant solution.

Here goes...

For XML string fields which may contain single or multiple entries, PHP treats them as either an array of strings or a string. Outputting them using count(array) results in either the correct results for arrays (array[index]) or the incorrect result for strings i.e. if count(array) = 1 then echo array[1] echoes the first character of the string.

I could apply extra coding simply to test the array count and provide different output routines for each scenario, but this seems a little dumb and I am sure there must be a better way...

Posted: Thu Jul 15, 2004 8:22 pm
by JAM
Not sure I follow, so if I'm suggesting something thats way of...

can'y you use the function is_array() for something useful?

Code: Select all

if (is_array($var)) {
  echo $var[0];
} else {
  echo $var;
}
If that didn't help, can you provide some small examples?

Posted: Thu Jul 15, 2004 11:46 pm
by stsr11
Thx for your prompt response.

Yeah, your right I could have explained it better...

Try this (PHP speak).

myarray["attr"][] = "Testing";
myarray["attr"][] = "and again!";
echo myarray["attr"][0]; // => "Testing" - (1st array element)

myarray["attr"] = "A string";
echo myarray["attr"][0]; // => "A" (1st character)

This is off the top of my head. I haven't tested it...

The problem is because the array is being created from XML, my data will regularly generate both 1 & multiple array counts. I want to avoid, if possible, doing code for every instance to check for the 2 possible scenarios...

Any ideas?

Posted: Thu Jul 15, 2004 11:57 pm
by feyd

Code: Select all

if(is_string($myarray['attr']))) $myarray['attr'] = array($myarray['attr']);
then process like it normal (array)