View Full Version : load empty array dynamically

12-01-2010, 09:20 AM
I am trying to populate an empty array based on attribute values in an xml file. Surprised to find out that PHP requires the array to be filled manually in advance. Is there a way to populate an array full of values through a loop like foreach()

Here is what I have so far:

$xml_attribute_id = array();
$i = 0;
foreach($id as $node)
$xml_attribute_id[$i] = $node["id"];

$id refers to a reference of gathering attributes from a specific element found repeatedly in an xml file.

maybe I could give it one value like 0 in the array and use array_push() like thus:

$xml_attribute_id = array(0);
$i = 0;
foreach($id as $node)
array_push($xml_attribute_id, $node["id"]);

Tried this and it didnt work. Any thoughts?

Thanks a lot

12-01-2010, 01:11 PM
assuming that $node["id"]; actually has a value..

$xml_attribute_id[] = $node["id"];

the $i is not required as php will index it automagically , if $node['id'] has no value you will get a warning + an empty array value.

not really sure what you are doing, but if you want to generate a non-empty array you could look at range (http://www.php.net/manual/en/function.range.php) or array_fill (http://www.php.net/manual/en/function.array-fill.php)

12-01-2010, 01:13 PM
$xml_attribute_ids = array();
foreach($id as $node) {
$xml_attribute_ids[] = (string)$node["id"];

When saving XML node data, you should typecast it as I did with (string) - otherwise PHP stores it as a XML object, which will work but waste memory, cpu time and potentially screw up serialisation, comparisons etc.