Initialize an array of associative arrays in PHP

1

I know that to declare an array is done in the following way:

public $hijo = array();
// ó
public $hijo[];

and for an associative array:

 public $hijo = array (
    'idPregunta' => '',
    'codigo' => '',
    'pregunta' => ''
);

Now, I try to declare a array of associative arrays in the following way:

public $hijo[] = array (
    'idPregunta' => '',
    'codigo' => '',
    'pregunta' => ''
);

but I get the following error:

  

PHP Parse error: syntax error, unexpected '[', expecting ',' or ';'

What is the correct way to do this?

    
asked by Rene Limon 20.02.2017 в 21:53
source

2 answers

0

You do not need the [] before the content. You can declare it in two ways:

A. With the array constructor ()

public $hijo = 
  array (
    'idPregunta' => '1',
    'codigo' => '01',
    'pregunta' => '¿por qué puso ud []'
   );

According to the PHP Manual:

  

An array can be created with the language constructor array (). It takes any number of key pairs = > value as arguments.

array(
        clave  => valor,
        clave2 => valor2,
        clave3 => valor3,
        ...
)
     

The comma after the last element of the array is optional, and it can be omitted. This is normally done for arrays of a single line, that is, it is preferable to have an array (1, 2) than an array (1, 2,). On the other hand, for multiline arrays, the final comma is frequently used, since it allows a simpler addition of new elements at the end.

     

Documentation about array in the PHP Manual

As of PHP 5.4 you can also use the short array syntax, which allows you to replace array() with [] .

B. As of PHP 5.4: using [ ] perooo ...

enclosing the contents of the array in brackets, not placing brackets after the name of the variable:

// a partir de PHP 5.4
$array = 
  [
    "foo" => "bar",
    "bar" => "foo",
  ];

C. Multidimensional array

It is declared in the same way:

$array = 
    array(
          "foo" => "bar",
          42    => 24,
          "multi" => array(
                            "dimensional" => 
                               array(
                                      "array" => "foo"
                                     )
                           )
          );
    
answered by 20.02.2017 / 22:00
source
1

public is to declare the visibility of a property or method to members of a class.

$hijo = []; // iniciar array

$hijo[] = [
    'idPregunta' => '',
    'codigo' => '',
    'pregunta' => ''
];

print_r($hijo);

See example

As of PHP 5.4 you can also use the short array syntax, which replace array() with [] .

    
answered by 20.02.2017 в 22:01