Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    May 2008
    Posts
    446
    Thanks
    23
    Thanked 5 Times in 5 Posts

    load empty array dynamically

    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:

    Code:
    $xml_attribute_id = array();
    	$i = 0;
    	foreach($id as $node)
    	{
    		$xml_attribute_id[$i] = $node["id"];
    		$i++;
    	}
    $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:

    Code:
    $xml_attribute_id = array(0);
    	$i = 0;
    	foreach($id as $node)
    	{
    		array_push($xml_attribute_id, $node["id"]);
    		$i++;
    	}
    Tried this and it didnt work. Any thoughts?

    Thanks a lot
    Ben

  • #2
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    assuming that $node["id"]; actually has a value..
    PHP Code:
    $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 or array_fill
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #3
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts
    PHP Code:
    $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.
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •