Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8649047
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T13:27:46+00:00 2026-06-12T13:27:46+00:00

The following is a print_r of an array converted from an XML document: Array

  • 0

The following is a print_r of an array converted from an XML document:

Array
    (
        [layer1] => Array
            (
                [item] => Array
                    (
                        [item-id] => 1886731
                        [item-name] => Bad Dog
                        [category] => pets
                        [link] = http://www.baddog.com/
                    )
            [total-matched] => 1
        )
    )

For the above array, sizeof($myarray[layer1][item]) should return 1, but it returns 4. I get the correct number of “item” items if there are more than one of them. The same error happens regardless of whether I use “sizeof” or “count”. How do I get PHP to return “1” when there is only one item?

Consequently, if there is one item, I can’t access item-name using array[layer1][item][0][item-name], I have to use array[layer1][item][item-name].

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T13:27:48+00:00Added an answer on June 12, 2026 at 1:27 pm

    There is a world of difference between:

    $array1 = array(
      'layer1' => array(
        'item' => array(
          '0' => array(
            'item-id' => 123123,
            'item-name' => 'Bad Dog',
            'category' => 'pets',
            'link' => 'http://www.baddog.com/',
          ),
        )
      )
    );
    

    and:

    $array2 = array(
      'layer1' => array(
        'item' => array(
           'item-id' => 123123,
           'item-name' => 'Bad Dog',
           'category' => 'pets',
           'link' => 'http://www.baddog.com/',
        )
      )
    );
    

    Basically they are different structures, and PHP is correct to return the following:

    count($array1['layer1']['item']);
    /// = 1 (count of items in the array at that point)
    
    count($array2['layer1']['item']);
    /// = 4 (count of items in the array at that point)
    

    If you wish to get a count for ['layer1']['item'] that makes sense to your app, you will always need ['layer1']['item'] to be an array containing multiple array structures… i.e. like $array1 above. This is the reason why I ask what is generating your array structure because – whatever it is – it is basically intelligently stacking your array data depending on the number of items, which is something you don’t want.

    Code that can cause an array to stack in this manner normally looks similar to the following:

    /// $array = array(); /// this is implied (should be set elsewhere)
    
    $key = 'test';
    $newval = 'value';
    
    /// if we are an array, add a new item to the array
    if ( is_array($array[$key]) ) {
      $array[$key][] = $newval;
    }
    /// if we have a previous non-array value, convert to an array
    /// containing the previous and new value
    else if ( isset($array[$key]) ) {
      $array[$key] = array($array[$key],$newval);
    }
    /// if nothing is set, set the $newval
    else {
      $array[$key] = $newval;
    }
    

    Basically if you keep calling the above code, and tracing after each run, you will see the following structure build up:

    $array == 'value';
    

    then

    $array == array(0 => 'value', 1 => 'value');
    

    then

    $array == array(0 => 'value', 1 => 'value', 2 => 'value');
    

    It’s the first step in this process that is causing the problem, the $array = 'value'; bit. If you modify the code slightly you can get rid of this:

    /// $array = array(); /// this is implied (should be set elsewhere)
    $key = 'test';
    $newval = 'value';
    
    /// if we are an array, add a new item to the array
    if ( is_array($array[$key]) ) {
      $array[$key][] = $newval;
    }
    /// if nothing is set, set the $newval as part of an subarray
    else {
      $array[$key] = array($newval);
    }
    

    As you can see all I’ve done is delete the itermediate if statement, and made sure when we discover no initial value is set, that we always create an array. The above will create a structure you can always count and know the number of items you pushed on to the array.

    $array == array(0 => 'value');
    

    then

    $array == array(0 => 'value', 1 => 'value');
    

    then

    $array == array(0 => 'value', 1 => 'value', 2 => 'value');
    

    update

    Ah, I thought so. So the array is generated from XML. In this case I gather you are using a predefined library to do this so modifying the code is out of the question. So as others have already stated, your best bet is to use one of the many XML parsing libraries available to PHP:

    http://www.uk.php.net/simplexml

    http://www.uk.php.net/dom

    When using these systems you retain more of an object structure which should be easier to count. Both the above also support xpath notation which can allow you to count items without even having to grab hold of any of the data.

    update 2

    Out of the function you’ve given, this is the part that is causing your arrays to stack in the manner that is causing the problem:

    $children = array();
    $first = true;
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                if($first){
                    $temp = $children[$elementName];
                    unset($children[$elementName]);
                    $children[$elementName][] = $temp;
                    $first=false;
                }
                $children[$elementName][] = $value;
            }else{
                $children[$elementName] = array($children[$elementName],$value);
            }
        }
        else{
            $children[$elementName] = $value;
        }
    }
    

    The modification would be:

    $children = array();
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                $children[$elementName][] = $value;
            }
        }
        else{
            $children[$elementName] = array($value);
        }
    }
    

    That should stop your arrays from stacking… however if you have any other part of your code that was relying on the previous structure, this change may break that code.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following data from print_r($_SESSION) : Array ( [totalprice] => 954 [cart]
print_r($array) results I retrieved some values from database and got the following result while
<?php print_r($response->response->docs); ?> Outputs the following: Array ( [0] => Object ( [_fields:private] =>
The following code: print_r($_GET); echo '<br />'; echo isset($_GET['logout'])?'yes':'no'; prints: Array ( [logoout] =>
I have the following code $result = $handle->select()->from('store_products_id', array('count'=>'COUNT(store_products_id.product_id)')) ->where('store_products_id.store_id=?', $this->store_id) ->columns($selectColumns) ->join('product_quickinfo', 'store_products_id.product_id
I have an array which is generated from an XML file and it shows
I have the following XML $data = <data> <element name='A'>value1</element> <element name='B'>value2</element> <element name='C'>value3</element>
I have the following array (in php after executing print_r on the array object):
The following code: $options = $value[$i]['options']; print_r($options); outputs the following result: Array ( [0]
I have the following model that print_r shows Array ( [id] => 1 [cms_name]

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.