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...
Help a PHP newbie with strings/arrays/xml?
Moderator: General Moderators
Not sure I follow, so if I'm suggesting something thats way of...
can'y you use the function is_array() for something useful?
If that didn't help, can you provide some small examples?
can'y you use the function is_array() for something useful?
Code: Select all
if (is_array($var)) {
echo $var[0];
} else {
echo $var;
}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?
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?
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
Code: Select all
if(is_string($myarray['attr']))) $myarray['attr'] = array($myarray['attr']);