What are the advantages of using associative arrays?

Asked

Viewed 669 times

16

I came across the definition of associative arrays which are vectors with indices consisting of strings, example:

$site['nome'] = "Stack Overflow";

What are the advantages of using this type of vectors? Since you can’t use them in a repeat structure, this can be a demerit of using this type of array. This method would be the way to make a struct or dictionary in PHP?

2 answers

21


According to the manual, the arrays PHP associatives are "ordered maps". There are a multitude of situations in which they can be useful.

Loops

The premise is not correct, you can use in a repetition structure without problems:

$teste = array( 'banana' => 'fruta', 'alface' => 'verdura' );
foreach( $teste as $key => $value ) {
   echo "$key é $value<br>\n";
}


Dbs

There are numerous situations to use associative arrays makes life easier. One of them, for example, is in the return of a line of a DB.

It’s much easier for you to understand a code with $campos['nome'], $campos['idade']... than $campos[1], $campos[2] ...

Also, if you use numeric indexes in this case, it creates a huge confusion in the code every time you add or remove a field from your query original.

In PHP especially, there are many functions to work with associative arrays, both working with key and value, and each of the parts separately.


JSON

Another use in which associative arrays are fundamental, is when you need to work with JSON.

Of course, this here:

"phoneNumbers": [
{
  "type": "home",
  "number": "212 555-1234"
},
{
  "type": "office",
  "number": "646 555-4567"
}

It can be represented like this:

array( "phoneNumbers" =>
   array( 
      array( "type" => "home", "number" => "212 555-1234" ),
      array( "type" => "office", "number" => "646 555-4567" )
   )
)

and vice versa. PHP already has native functions that convert one format to another.


Web forms

Within the overriding function for which it was designed, PHP naturally uses the arrays to receive data from HTML forms, and from query string, usually through the variables $_POST and $_GET, among others.

This here:

<input type="text" name="batatinha">

when received by PHP, it becomes that:

$_POST['batatinha']

or in this, depending on the method:

$_GET['batatinha']

More practicality is even more difficult to imagine. This applies to numerous other situations, such as uploading files, for example.

Imagine if we had to count how many fields the form has, to access this information sequentially.

  • Question of n00b in PHP: And when you need a number-indexed array, #like? Associative arrays again or the language offers some other way?

  • I already found it here. An associative array is used in which the keys must be integer values, sequential and initiated by zero. Or build the array by passing only the values and omitting the keys, which will be implicit and obeying this behavior of being integer, sequential and initiated by zero.

  • @Piovezan the associative with numeric falls well when it needs to skip some number in the sequence as well, or when you need to reorder, but keeping the original indexing.

10

In fact they can have various types of data with keys, not only strings.

Its main feature is that the data is sparsely stored, i.e., it does not follow a continuous sequence, such as arrays common. Obviously this has its drawbacks there.

It really is a dictionary, also called a table hash or value map. In PHP is used to simulate struct, since PHP has nothing similar. Some will say that a class can simulate a struct. True, but what many don’t know is that the PHP class is a form of array associative, it is not a simple and continuous structure as it is in C or other typically static languages.

It can be used in a repeat structure yes, it can access all values one by one, only its internal organization is different.

In PHP it is widely used to receive data that comes externally from the web server or by a database query.

  • One thing I noticed is that if you declare an associative array with some elements in a certain order, and traverse that array in a for, it respects the order of creation. So maybe they’re not just hash tables, being more for those ordered maps, right? Because in a hash table the insertion order is not preserved when going through the keys, if I’m not mistaken.

  • @Piovezan yes, not quite hash, I put it simply, it’s probably a binary tree. These dynamic languages make objects all the same, it’s an ordered dictionary that gets confused with hash, but for having order, it is not. has my answer that I talk more details about it, I did not put here. I will see if better about it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.