Help a PHP newbie with strings/arrays/xml?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
stsr11
Forum Newbie
Posts: 17
Joined: Thu Jul 15, 2004 6:57 pm

Help a PHP newbie with strings/arrays/xml?

Post 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...
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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?
stsr11
Forum Newbie
Posts: 17
Joined: Thu Jul 15, 2004 6:57 pm

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

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