Query about opening array form in PHP

Asked

Viewed 36 times

0

Giving a read on arrays in PHP, I ended up finding some different ways to open an array, but in the end have the same destination, example:

$arr = [
   'dado' => ''
];

Or

$arr = array(
  'dado' => ''
);

Or

$arr['dado'] = '';

And in another context, adding Keys:

$a = 1;
while($a <= 10){
   $arr[$a] = 'dado'.$a;
   $a++
}

Is there any relevant difference in these different ways of opening an array ?

What would be the most 'correct' way to open an array ?

  • The last two do not generate the expected result. Do you really want to keep them in question? I think, considering the focus of the discussion, they could be removed.

  • I did not test to see if the return is the same, I think we can remove yes.

  • Look over dynamic languages. Which is the case for PHP, it will give the type of the variable at the time of assigning the value to it. As you declared the array in 3 forms, it will understand that the variable is of type array. It happens the same with javascript that has dynamic typing.

1 answer

0


Yes there is (when using, both generate the same result an array.), the compact syntax ([]) is only available from 5.4 for earlier versions only array() works. To maintain greater code compatibility if it is a library it is recommended to use traditional syntax array().

Browser other questions tagged

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