Hi There -

Keep running into different ways of creating arrays in Drupal. It feels like learning a foreign language, I can understand and modify, but not speak. Now that I'm wanting to make arrays, I'm noticing differences that I don't quite understand. Here are two methods that I've run into. If there are more, please let me know!

Here's the first way - the way with hash marks - what do they actually mean?:

<?php
$contents['message'] = array(
        '#type' => 'select',
        '#title' => t('Choose one of these'),
        '#options' => drupal_map_assoc($message_options),
        '#default_value' => 'Awp!',
      );    
?>

Here's the second way - the one without hash marks:

<?php
$contents[] = array(
    'id' => 'container',
    'callback' => 'my_function',
    'title' => t('These are contents'),
    'desc' => t('Look at these contents'),
    'weight' => 7,
  );
?>

What is the difference in the characteristics of the arrays these two methods produce?

Comments

j_ten_man’s picture

The hashmarks are the way that drupal handles forms. As far as I know they don't mean anything special. It just seems to be the way that they designed it. Of course, that could be wrong, but it is just an associative PHP array either way. The arrays are basically the same. They are both arrays of arrays, but the second one has a numerical key whereas the first one has a string for its key (thus an associative array). If you're not clear on the terminology, a quick Google search for associative PHP array should clear things up.

newbstah’s picture

And do I have the right idea here?

function get_element($parent_nid, $parent_type) {
  $result = db_query("SELECT title, type FROM {node} WHERE nid = %d, $parent_nid");
  $element[] = array (
    'title' => $result -> title,
    'type'  => $result -> type,
    'nid'   => $parent_nid
  )

j_ten_man’s picture

Almost - you need to use db_fetch_object and get your $parent_nid outside of the quotes:

function get_element($parent_nid, $parent_type) {
  $results = db_query("SELECT title, type FROM {node} WHERE nid = %d", $parent_nid);
  if($result = db_fetch_object($results)){
    $element[] = array (
      'title' => $result -> title,
      'type'  => $result -> type,
      'nid'   => $parent_nid
    );
  }
}
zeta ζ’s picture

It makes no difference to the array, just the keys are called eg. '#title' instead of 'title'.

If the array is for a form, use the '#' See http://api.drupal.org/api/file/developer/topics/forms_api_reference.html/5 and search the page for '# '.
___________________
It’s in the detaιls…

demonstration portfolio

newbstah’s picture

Wow! Thank you all for your quick replies! I hope this thread saves someone else confusion.

Let me know if I'm right here:

Would this array:

<?php
  $element[] = array (
    'title' => $result -> title,
    'type'  => $result -> type,
    'nid'   => $parent_nid
  )
?>

produce a print_r that looked like this?

<?php
[element] => Array
    (
        [0] => Array
            (
                [title] => A life of happiness
                [type] => story
                [nid] => 45
            )
    )
?>

If I did this:

<?php
  $element = array (        // <-------------- took out square brackets
    'title' => $result -> title,
    'type'  => $result -> type,
    'nid'   => $parent_nid
  )
?>

Would I get this?

<?php
[element] => Array
    (
        [title] => A life of happiness
        [type] => story
        [nid] => 45
    )
?>

Another confounding question for me about arrays is when do you use brackets, and when do you use arrows when addressing their elements?

What's the difference between saying:
$result['title']
and
$result->title?

I'll see $result[first]->title,
but never $result ->first->title.

I'll see $result ->[first][title] (I think)
but never $result ->[first]->title.

What are the differences between them? What's the correct grammar to use?

nevets’s picture

Square brackets are used for arrays, -> is used to reference an element of an object. So $result['title'] accessed the array element of $result with an index of 'title' while $result->title access the title element of $result. While you can cast an array to an object (an vis-a-versa) you need to use the correct syntax based on what type $result is.

Side note, while you will still see $result[first] used one should always use quotes around the string.

And both $result['first']->title is valid if $result is an array of objects and so is $result->first->title if $result is an object and the element first is also an object.

Neither $result ->['first']['title'] or $result ->['first']->title are valid syntax. One can read -> as points to so $result-> must point to a valid element.

newbstah’s picture

Hi and Thank you!

Just to get this out of the way, since you didn't comment on the first part of my last post, should I assume I'm right there - with the different syntax producing the different print_r's ?

What if I have an array within an object? Suppose '$result' is an object and 'element' is an array within the object with children: 'type', 'nid' and 'title'?

Would I address the title of the element as:
$result -> element['title'] ?

Is this correct?

nevets’s picture

Correct, if $result' is an object and 'element' is an array within the object with children: 'type', 'nid' and 'title'?

You I address the title of the element as:
$result -> element['title']

yelvington’s picture

This really isn't a Drupal issue but rather a basic PHP issue. I would urge that you spend some time with the PHP manual, and maybe a good PHP book if you can find one, so that you get a thorough understanding of how PHP handles arrays.

Drupal makes heavy use of arrays, and in many cases they are arrays containing a mix of goodies, possibly more arrays.

  $element[] = array (
    'title' => $result -> title,
    'type'  => $result -> type,
    'nid'   => $parent_nid
  )

It's important to understand that when you say $element[] = something, you're actually ADDING to an array. In this example, you're adding a member that itself is an associative array.

An associative array has keys that correspond with values, which is why you see the 'key' => 'value' notation. In an indexed array, the keys are omitted (PHP supplies numbers instead).

Apparently this was the first member of $element, so it was assigned the index of 0. That's why you got this result:

[element] => Array
    (
        [0] => Array
            (
                [title] => A life of happiness
                [type] => story
                [nid] => 45
            )
    )

Try repeating your assignment code three times, and print_r should give you this:

[element] => Array
    (
        [0] => Array
            (
                [title] => A life of happiness
                [type] => story
                [nid] => 45
            )
        [1] => Array
            (
                [title] => A life of happiness
                [type] => story
                [nid] => 45
            )
        [2] => Array
            (
                [title] => A life of happiness
                [type] => story
                [nid] => 45
            )
    )

Get it? When you include the [] you tell PHP to assign a new member to the $element array, which already may have some goodies in it.

When you omit the [] you tell PHP to clobber the $element variable with the member.

This technique is very widely used in Drupal so one API function can process any number of elements. It how a form is built: You add elements at will, and let the system sort out the mess later. Other modules can reach in an alter your elements before the form is rendered. Very powerful. But you have to start with a level of comfort with PHP's array notation.

newbstah’s picture

Wow! Thanks! You guys are great!

You've all cleared up a lot for me.

If I want to get the nid of the third array above, I'd address it as:
$whatever[element][2][nid]

Is this correct?

nevets’s picture

From the example dump I think you want $element[2]['nid']. While print_r does not quote string indexes your code should.

newbstah’s picture

Thank you again! I feel a lot more confident taking Drupal now. This stuff is crucial and you've given me a lot to work with. I hope something wonderful happens to all of you this week!